在JSX事件函数方法中的 this,默认不会绑定 this指向。如果你忘记绑定,当你调用这个函数的时候 this 的值为 undefined。所以使用时一定要绑定好this的指向。
- 构造方法中绑定
constructor(props){
super(props)
// 在构造方法中指定this指向 <button onClick={this.fun()}>按钮</button>
this.fun = this.fun.bind(this)
}
import React, { Component } from 'react'
export default class Userthis extends Component {
// 方案解决this指向问题
constructor(props) {
super(props);
// 手动绑定this的指向
// this.fn = this.fn.bind(this)
}
render() {
return (
<div>
{/* <button onClick={this.fn}>获取父组传过来的数据</button> */}
{/* 方案2 在绑定方法中使用bind */}
{/* <button onClick={this.fn.bind(this)}>获取父组传过来的数据</button> */}
{/* 方案3 箭头函数绑定 */}
{/* <button onClick={() => this.fn()}>获取父组传过来的数据</button> */}
{/* 方案4 在绑定实现的方法中定义使用箭头函数 */}
<button onClick={this.fn}>获取父组传过来的数据</button>
</div>
)
}
// 方案4
fn = () => {
console.log(this.props)
}
/* fn() {
console.log(this.props)
} */
}
右侧赞助一下 代码改变世界一块二块也是爱
浙公网安备 33010602011771号