Three properties of component instances
1. Attribute I
state
[concept] React regards components as a state machine. Through the interaction with users, different states are realized, and then the UI is rendered to keep the user interface and data consistent.
[note]
- this in the render method of the component is the component instance object
- this is undefined in the method defined by the component. How to solve it?
a. Force binding this: through bind() of function object
b. Arrow function - Status data cannot be modified or updated directly
- Instead of modifying the State directly, use setState()
2. Attribute II
props
Subcomponents can only pass data through props
<script type="text/babel"> //1. Create components class Person extends React.Component { render() { const {name,age} = this.props; return ( <div> <ul> <li>full name:{name}</li> <li>Age:{age}</li> </ul> </div> ) } } //Restrict the type | necessity of label attributes (the React library file of PropTypes needs to be introduced here) Person.propTypes = { name: PropTypes.string.isRequired, sex: PropTypes.string, age: PropTypes.number, speak: PropTypes.func } //Limit the type and necessity of label attributes Person.defultProps = { sex:'female', age:18 } //2. Render component to page ReactDOM.render(<Person name="Zhang San" age="14"/>, document.getElementById('test1')); ReactDOM.render(<Person name="Lao Wang" age="18"/>, document.getElementById('test2')); function speak(){ console.log('I spoke'); } </script>
props shorthand (put all restrictions inside the class)
<script type="text/babel"> //1. Create components class Person extends React.Component { //Restrict the type and necessity of label attributes static propTypes = { name: PropTypes.string.isRequired, sex: PropTypes.string, age: PropTypes.number, speak: PropTypes.func } //Limit the type and necessity of label attributes static defultProps = { sex:'female', age:18 } render() { const {name,age} = this.props; return ( <div> <ul> <li>full name:{name}</li> <li>Age:{age}</li> </ul> </div> ) } } //2. Render component to page ReactDOM.render(<Person name="Zhang San" age="14"/>, document.getElementById('test')); function speak(){ console.log('I spoke'); } </script>
3. Attribute III
ref
ref is an interface provided by React to manipulate React component instances or DOM elements.
Three ways of ref
- ref in string form
<script type="text/babel"> //1. Create components class Demo extends React.Component { showIputDate = () => { const {input2} = this.refs; alert(input2.value); } render() { return ( <div> <input onBlur={this.showIputDate} ref="input2" type="text" placeholder="Lose focus get content" /> </div> ) } } //2. Render component to page ReactDOM.render(<Demo/>, document.getElementById('test')); </script>
- ref in callback form
<script type="text/babel"> //1. Create components class Demo extends React.Component { showDate = () => { const {input} = this; alert(input.value); } showIputDate2 = () => { const {input3} = this; alert(input3.value); } render() { return ( <div> <input type="text" ref={(e)=>{this.input=e;console.log("@",e)}} placeholder="Click the button to get the content" /> <button onClick={this.showDate}>Button</button> <input onBlur={this.showIputDate2} ref={(c) => {this.input3 = c}} type="text" placeholder="Lose focus get content" /> </div> ) } } //2. Render component to page ReactDOM.render(<Demo/>, document.getElementById('test')); </script>
- Use of ceateRef
<script type="text/babel"> //1. Create components class Demo extends React.Component { showIputDate = () => { const {input2} = this.refs; alert(input2.value); } showDate = () => { const {input} = this; alert(input.value); } saveInput=(e)=>{ this.input=e; console.log('@',e); } render() { return ( <div> <input type="text" ref={this.saveInput} placeholder="Click to get the input" /> <button onClick={this.showDate}>Button</button> <input onBlur={this.showIputDate} ref="input2" type="text" placeholder="Lose focus get content" /> </div> ) } } //2. Render component to page ReactDOM.render(<Demo/>, document.getElementById('test')); </script>
[emphasis] do not overuse refs
Uncontrolled and controlled components
Uncontrolled components
<script type="text/babel"> class Login extends React.Component{ onLogin = (event) => { //Block form submission event.preventDefault(); const {username,password} = this; alert(`The user name you entered is ${username.value},The password is ${password.value}`) } render() { return ( <form action="https://baidu.com" onSubmit={this.onLogin}> user name: <input ref={c => this.username=c} type="text" name="username"/> password:<input ref={c => this.password=c} type="text" name="password"/> <button>Submit</button> </form> ) } } ReactDOM.render(<Login/>,document.getElementById('test')); </script>
Controlled components
<script type="text/babel"> class Login extends React.Component{ // Get user name to state changeUsername = (event) => { this.setState({username:event.target.value}); } // Get password to state changePassword = (event) => { this.setState({password:event.target.value}); } onLogin = (event) => { //Block form submission event.preventDefault(); const {username,password} = this.state; alert(`The user name you entered is ${username},The password is ${password}`) } render() { return ( <form action="https://baidu.com" onSubmit={this.onLogin}> user name: <input onChange={this.changeUsername} type="text" name="username"/> password:<input onChange={this.changePassword} type="text" name="password"/> <button>Submit</button> </form> ) } } ReactDOM.render(<Login/>,document.getElementById('test')); </script>
concept
Higher order functions and corrilization of functions
Higher order function: if a function meets any of the following two specifications, the function is a higher order function.
- If the parameter accepted by A function is A function, then A can be called A higher-order function.
- If the return value of A function call is still A function, then A can be called A higher-order function.
a. Common high-order functions include Promise, setTimeout, arr.map(), etc
Coriolism of function: the function coding form in which the parameters are accepted for many times and finally processed uniformly is realized by continuing to return the function through function call.
example
class Login extends React.Component{ // Initialization status state = { username:'', //user name password: '' // password } // Get form data into status saveFromDate = (typeDate) => { return(event)=>{ this.setState({[typeDate]:event.target.value}); } } onSubmit = (event) => { //Block form submission event.preventDefault(); const {username,password} = this.state; alert(`The user name you entered is ${username},The password is ${password}`) } render() { return ( <form action="https://baidu.com" onSubmit={this.onSubmit}> user name: <input onChange={this.saveFromDate('username')} type="text" name="username"/> password:<input onChange={this.saveFromDate('password')} type="text" name="password"/> <button>Submit</button> </form> ) } } ReactDOM.render(<Login/>,document.getElementById('test'));
Implementation of coriolism without function
,<script type="text/babel"> class Login extends React.Component{ // Initialization status state = { username:'', //user name password: '' // password } // Get form data into status saveFromDate = (typeDate,event) => { this.setState({[typeDate]:event.target.value}); } onSubmit = (event) => { //Block form submission event.preventDefault(); const {username,password} = this.state; alert(`The user name you entered is ${username},The password is ${password}`) } render() { return ( <form action="https://baidu.com" onSubmit={this.onSubmit}> user name: <input onChange={event => this.saveFromDate('username',event)} type="text" name="username"/> password:<input onChange={event => this.saveFromDate('password',event)} type="text" name="password"/> <button>Submit</button> </form> ) } } ReactDOM.render(<Login/>,document.getElementById('test')); </script>
react life cycle (old and new)
- Components go through some specific stages from creation to death
- The React component contains the life cycle of a series of hook functions, which will be called at a specific time
- When defining components, we will do specific work in specific life cycle callback functions
Life cycle (old)
- Initialization phase: by reactdom Render() trigger - first render
1)constructor()
2) componentWillMount()
3) render()
4) Componentdidmount() = = = > common
Generally, initialization is done in this hook, such as starting the timer, sending network requests and subscribing to messages - Update phase: this. By the component Triggered by setsate() or parent component render
1) shouldComponentUpdate()
2) componentWillUddate()
3) Render() = = = > must use a
4)componentDidUpdate() - Uninstall components: by reactdom Unmountcomponentatnode() trigger
1) Componentwillunmount() = = = > common
Generally, you can do some closing things in this hook, such as closing the timer and unsubscribing messages
example
<script type="text/babel"> //Create component class Sum extends React.Component{ //constructor constructor(props){ console.log('count---constructor'); super(props) // Initialization status this.state = {count:0}; } //Add 1 button callback add = ()=>{ //Get original status let {count} = this.state; //Update status this.setState({count:count+1}) } //Callback for unload component button death = ()=>{ ReactDOM.unmountComponentAtNode(document.getElementById('test')); } //Callback of force Update button force = ()=>{ this.forceUpdate(); } //Hook on which the component will be mounted componentWillMount(){ console.log('count---componentWillMount'); } //Hook on which the component will be mounted componentDidMount(){ console.log('count---componentDidMount'); } //The hook that the component will unload componentWillUnmount(){ console.log('count---componentWillUnmount'); } //Updated "valves" for control components shouldComponentUpdate(){ console.log('count---shouldComponentUpdate'); return true; } //The hook that the component will update componentWillUpdate(){ console.log('count---componentWillUpdate'); } //Hook after component update componentDidUpdate(){ console.log('count---componentDidUpdate'); } render() { console.log('count---render'); return ( <div> <h2>Current summation is{this.state.count}</h2> <button onClick={this.add}>Point me+1</button> <button onClick={this.death}>uninstall</button> <button onClick={this.force}>Do not change the data in any state, and force the update</button> </div> ) } } //Parent component A class A extends React.Component{ //Initialization status state = {carName:'Ben Chi'} changeCar = ()=>{ this.setState({carName:'Alto'}) } render(){ return( <div> <div>I am A assembly</div> <button onClick={this.changeCar}>change</button> <B carName={this.state.carName}/> </div> ) } } //Sub assembly B class B extends React.Component{ //The component will accept the hook of the new props componentWillReceiveProps(props){ console.log('B---componentWillReceiveProps',props); } //Updated "valves" for control components shouldComponentUpdate(){ console.log('B---shouldComponentUpdate'); return true; } //The hook that the component will update componentWillUpdate(){ console.log('B---componentWillUpdate'); } //Hook after component update componentDidUpdate(){ console.log('B---componentDidUpdate'); } render(){ console.log('B---render'); return( <div>I am B Component, received vehicle:{this.props.carName}</div> ) } } //Rendering Components ReactDOM.render(<A/>,document.getElementById('test')); // ReactDOM.render(<Sum/>,document.getElementById('test')); </script>
Life cycle (New)
Differences between new and old versions of life cycle:
- The new version will discard three life hooks: componentWillUnmount, componentWillUpdate and componentWillReceiveProps
- Two new life hooks are proposed: getDerivedStateFromProps and getSnapshotBeforeUpdate