Core attribute 1: State
State: Applies to class components. The React class component has its own state and automatically refreshes the component when the state changes (executes the render method in the component).
Modify the state of
this.setState(nextState[,callback])
nextState: The new state to be set, which will be merged with the current statecallback: Optional argument, callback function. This function is called after setState has been set and the component has been rerendered.Copy the code
If you rely on the result of the last setState() : setState(fn [,callback])
this.setState((prevState) = > {
return { num: prevState.num + 1 };
});
Copy the code
Matters needing attention
- SetState () is asynchronous when used directly, synchronous when used in native events and setTimout
- Many times
setState()
Will automatically merge, but with the method of passing in functions, can not merge, passed in objects can setState()
Components are automatically refreshed and can also be usedforceUpdate()
Perform a manual forcible refresh
Core attribute 2: props
Props: Parent component passes child component
- Receiving mode
- Function component: Passes the first argument to a function
- Class component: accessed through this.props
For example,
<MyComponent data={100} name="tom"/ > values:this.props.data this.props.name
Copy the code
- Props type verification
Setting static propTypes to components sets type checkers for component properties, which can be useful when writing components to restrict the data types of properties passed in
- React built-in data type checker PropTypes
After React16, PropTypes was separated from the React package into the prop-types package
import PropTypes from "prop-types";
class MyComponent extends React.Component{
}
MyComponent.propTypes = {
name: PropTypes.string
}
---------------------------------------------
class MyComponent extends React.Component{
staic propTypes = {
name: PropTypes.string
}
}
Copy the code
Note: if you use TS you can completely replace the above notation
Props and state
State is the state of the component, which is readable and writable, and props is a property passed by the parent component
Core attribute 3: REF
- Applied position
- Applied to element nodes: References to nodes
- Applied to a component: A reference to a component instance
- Scenarios where ref is used
- Manage focus, text selection or media playback
- Trigger forced animation
- Integrate third-party DOM libraries
- Set mode
- Ref as a string
<input ref="input1"/ > values:this.refs.input1
Copy the code
- Refs in callback form
<input ref={c= > this.input1 = c} is equivalent to assigning the current node (DOM) (input field) to the instance attribute of the component.this.input1
Copy the code
- createRef
myRef = React.createRef()
<input ref={this.myref} /> Values:this.myRef.current
Copy the code
Note that function components cannot use ref