对于 Vue 而言,它本身内置了v-model这样的语法糖,可以帮我们进行双向绑定,但是 React 在很大程度上需要自己来进行设置。

  1. import React from 'react'
  2. import ReactDOM from 'react-dom'
  3. class TxtInput extends React.Component {
  4. constructor(props){
  5. super(props) // super() 类似于调用父类(React.Component)的构造函数
  6. this.state = {
  7. txtValue: ""
  8. }
  9. }
  10. handleChange(e){
  11. /*
  12. 将文本框 value 传给状态对象的 txtValue 属性中
  13. value 在 `e.target.value` 属性中
  14. */
  15. this.setState({
  16. txtValue: e.target.value
  17. })
  18. }
  19. render(){
  20. return (
  21. <div className="input-box">
  22. <input
  23. value={this.state.txtValue} /* 将 input 值和 txtValue 属性绑定,实现单向传输数据 */
  24. onChange={ (e)=> this.handleChange(e) } /* 更新 txtValue 的值 */
  25. >
  26. </div>
  27. )
  28. }
  29. }
  30. ReactDOM.render(<TxtInput/>, document.getElementById("root"))

小结

在整个过程中,我们并没有通过 this.state.txtValue 的值和 input标签中的 value 属性进行绑定,而是通过:

  • value={this.state.txtValue}来实现 value 动态与 txtValue 值相同
  • 通过 onChange 事件来监听value的变化,利用handleChange()这个函数,来对状态中的txtValue进行更新。