this指向
- 箭头函数
onchange() {
this.setState({
...
})
}
render() {
return (
<div>
//使用箭头函数的this指向,让这个this指向render方法
<button onClick={() => {this.onchange()}}>+1</button>
</div>
)
}
- 使用 function.prototype.bind()
constructor() {
super()
// 初始化 state
this.state = {
count : 0
}
// 使用 bind() 方法将事件处理程序的this和组件实例绑定到一起
this.onChangeState = this.onChangeState.bind(this)
}
- 使用 class 实例方法
onChangeState = () => {
this.setState({
count : this.state.count + 1
})
}
render() {
return (
<div>
<h1>计算机: { this.state.count }</h1>
<button onClick={this.onChangeState()}>+1</button>
</div>
)
}
表单处理
-
受控组件
-
React 将 state 和 表单元素中的 value 绑定到一起,由state 值的变化进行控制表单元素的变化
-
使用步骤:
- 在 state 添加一个状态,作为表单元素的 value 值
state = { txt : '' } <input type="text" name='txt' value={this.state.txt} />
- 在表单元素中绑定 change 事件,将表单元素的值 设置为 state 的值
handleChange() { this.setState({ txt : e.target.value }) } <input type="text" name='txt' value={this.state.txt} onChange = {this.handleChange}/>
-
-
非受控组件:借助 ref ,使用原生 DOM 方法来获取表单元素值
- 调用 React.createRef() 方法创建一个 ref 对象
constructor() { super() this.txtRef = React.createRef() }
- 将创建好的 ref 对象添加到文本框中
<input type = "text" ref = {this.txtRef} />
- 通过ref 对象获取到文本框的值
console.log(this.txtRef.current.value)