【发布时间】:2019-04-12 09:27:30
【问题描述】:
基本上我们在构造函数中绑定事件处理函数,或者在 React 类组件中将它们作为箭头函数,如下所示
class Test extends Component{
constructor(props){
super(props);
this.state = { count:0 };
this.setCount = this.setCount.bind(this);
}
setCount() {
this.setState({count: this.state.count + 1});
}
render() {
return <button onClick={this.setCount}>Increase</button>
}
}
但是在 React v16.7.0 中引入了钩子之后,类组件变成了有状态的函数式组件。
那么如何在函数组件中绑定函数和钩子呢?
【问题讨论】:
-
没有必要在函数组件中绑定函数,因为你没有使用
this。 -
用箭头功能就不需要了
-
好的,如果我使用带有 mapStateToProps 的 Redux 连接方法。如何访问 this.props 等功能组件中的 props 或仅访问 props?
-
你只是使用道具...而不是this.props
标签: javascript reactjs react-native react-hooks