1. this

import React from 'react'; class SingleSelectComponent extends React.Component { constructor(props) { super(props); this.state = { value: 'cute' }; } handleChange() { this.setState({ value: e.target.value }); } handleSubmit(e) { console.log(this); console.log(this.state.value); e.preventDefault(); } render() { return ( <form onSubmit={(e) => { this.handleSubmit(e) }}> <label> <select value={this.state.value} onChange={this.handleChange}> <option value="sunshine">sunshine</option> <option value="handsome">handsome</option> <option value="cute">cute</option> <option value="reserved">reserved</option> </select> </label> <input type="submit" Value =" Submit "/> </form>)}} export default SingleSelectComponent;Copy the code

In the above example, onSubmit is followed by the arrow function. This points to an instance of the SingleSelectComponent, so there is no need to modify this, while onChange is followed by this.handleChange. The react function is undefined, so you need to change the “this” reference.

Modify this as follows:

  • Bind this in constructor
constructor(props) {
    super(props);
    this.state = { value: 'cute' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}
Copy the code
  • Use the arrow function definition
handleChange = () => {
    this.setState({ value: e.target.value });
}
handleSubmit = (e) => {
    console.log(this);
    console.log(this.state.value);
    e.preventDefault();
}
Copy the code
  • Use the arrow function in Render
 <form onSubmit={(e) => { this.handleSubmit(e) }}></form>
Copy the code

2. Controlled components and uncontrolled components

Controlled component: A component controlled by state or props updates the state in real time through onChange, or updates the state of the parent component by executing the parent component. Application scenarios: 1. Verify input content in real time. 2. Associative content display in the search box.

Uncontrolled component: A component that is not controlled. Obtain the content of DOM corresponding to input through ref method to obtain value.