对于 Vue 而言,它本身内置了v-model
这样的语法糖,可以帮我们进行双向绑定,但是 React 在很大程度上需要自己来进行设置。
import React from 'react'
import ReactDOM from 'react-dom'
class TxtInput extends React.Component {
constructor(props){
super(props) // super() 类似于调用父类(React.Component)的构造函数
this.state = {
txtValue: ""
}
}
handleChange(e){
/*
将文本框 value 传给状态对象的 txtValue 属性中
value 在 `e.target.value` 属性中
*/
this.setState({
txtValue: e.target.value
})
}
render(){
return (
<div className="input-box">
<input
value={this.state.txtValue} /* 将 input 值和 txtValue 属性绑定,实现单向传输数据 */
onChange={ (e)=> this.handleChange(e) } /* 更新 txtValue 的值 */
>
</div>
)
}
}
ReactDOM.render(<TxtInput/>, document.getElementById("root"))
小结
在整个过程中,我们并没有通过 this.state.txtValue
的值和 input标签中的 value
属性进行绑定,而是通过:
value={this.state.txtValue}
来实现value
动态与txtValue
值相同- 通过
onChange
事件来监听value
的变化,利用handleChange()
这个函数,来对状态中的txtValue
进行更新。