Data binding in React

前端 未结 12 776
心在旅途
心在旅途 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:34

    Data binding in React can be achieved by using a controlled input. A controlled input is achieved by binding the value to a state variable and a onChange event to change the state as the input value changes.

    See the below snippet

    class App extends React.Component {
      constructor() {
        super();
        this.state = { value: 'Hello World' };
      }
      handleChange = (e) => {
        this.setState({ value: e.target.value });
      };
      render() {
        return (
          

    {this.state.value}

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


    Update: React Hooks

    Here is an equivalent function component of the class defined above.

    const { useState } = React;
    
    const App = () => {
      const [value, setValue] = useState('Hello World');
      const handleChange = (e) => setValue(e.target.value);
      return (
        

    {value}

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

提交回复
热议问题