React实现双向数据绑定

1.首先创建一个组件,初始化一个变量来显示数据
2.想实现双向数据绑定的效果,需要在input输入框中添加一个onChange事件
3.在事件中,把取到的值用setState重新写在定义的state里面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React实现双向数据绑定</title>
</head>
<body>
  <div id="root"></div>

  <script src="./lib/react.js"></script>
  <script src="./lib/react-dom.js"></script>
  <script src="./lib/babel.js"></script>

  <script type="text/babel">
    class App extends React.Component {
      constructor() {
        super()
        this.state = {
          value:'123'
        }
      }

      handleChange(e) {
        console.log(e.target)
        this.setState({value: e.target.value})
      }

      render() {
        return (
          <div>
            <input 
              type="text" 
              value={this.state.value}
              onChange={e => this.handleChange(e)} 
            />
            <h1>{this.state.value}</h1>
          </div>
        )
      }
    }

    const root = ReactDOM.createRoot(document.querySelector('#root'))
    root.render(<App/>)
    
  </script>

Github: https://github.com/ztw1002/React_Demo/blob/main/React实现双向数据绑定/index.html

posted @ 2023-06-20 13:25  ztw1002  阅读(201)  评论(0编辑  收藏  举报