Data binding in React

前端 未结 12 992
心在旅途
心在旅途 2021-01-30 19:49

What I want to do is when I type some text in an input field, it should appear in another place realtime.

Below is my input;



        
12条回答
  •  情书的邮戳
    2021-01-30 20:39

    To bind a control to your state you need to call a function on the component that updates the state from the control's event handler.

    Rather than have an update function for all your form fields, you could create a generic update function using ES6 computed name feature and pass it the values it needs inline from the control like this:

    class LovelyForm extends React.Component {
      constructor(props) {
      alert("Construct");
        super(props);
        this.state = {
          field1: "Default 1",
          field2: "Default 2"
        };
      }
    
      update = (name, e) => {
        this.setState({ [name]: e.target.value });
      }
    
      render() {
        return (
          

    this.update("field1", e)} /> {this.state.field1}

    this.update("field2", e)} /> {this.state.field2}

    ); } } ReactDOM.render(, document.getElementById('example'));
    
    
    

提交回复
热议问题