The Render method does not override an element initialized in the constructor.

I am new to reaction and experimented when I noticed behavior with controlled form elements. I have a controlled input element whose value is bound to the state of the parent component, and its onChange handler accepts the entered value from the user and updates the state. Therefore, each time the user enters something, the input value reflects the change. This is the desired effect. It works great when the input is created in a render function. But in the event that the input is initialized through the class variable that is specified in the constructor, the same input does not update its value when the state changes. The only difference is that the first initialization element is initialized. What can cause this behavior? Any help is appreciated!

Here is an example of what code might cause the wrong behavior:

class App extends React.Component {
  
  constructor(props){
    super(props);
    this.state = {
      val : '',
    }
    this.handleChange = this.handleChange.bind(this);
    this.input = (
    <input type="text" 
           onChange={this.handleChange } 
           value={this.state.val} />
    );
  }
  
  handleChange(e){
   this.setState({val:e.target.value});
  }
  render() {

    return (
      <div className="App">  
        { this.input ? this.input : null }                
      </div>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Run codeHide result
+4
2

React . , .

, /,

  • componentWillReceiveProps()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • ()
  • componentDidUpdate()

- , refs.

render() {
  <input type="text" 
    onChange={this.handleChange } 
    value={this.state.val}
    ref={ ele => (this.input = ele)} 
  />
}

refs

+3

( ) . , , .

this.input , <input>, :

this.input = () => (
    <input type="text" 
       onChange={this.handleChange } 
       value={this.state.val} />
);

this.input() . .

, (this.input), , , prop ref:

render() {
  <input type="text" 
    onChange={this.handleChange } 
    value={this.state.val}
    ref={input => (this.input = input)}  // the magic happens here
  />
}

this.input .

+3

Source: https://habr.com/ru/post/1695038/


All Articles