我知道他们是类似的问题,但是我仍然对以下内容感到困惑。何时使用这样的状态Class Example extends Component { state = { name: '' } }过度构造器道具Class Example extends Component{ constructor(props) { super(props); this.state = { name: '' } }}它与方法绑定有关吗?因为我可以很好地使用onChange而不用像这样绑定它:this.onChange = this.onChange.bind(this) 我仍然可以像这样调用onChangeonChange = (e) => {}<Component onChange = {this.onChange} />
2 回答

蛊毒传说
TA贡献1895条经验 获得超3个赞
在反应新版本中,您可以直接初始化状态,而无需使用此
constructor(Props){
super(props)
this.state ={
}
}
他们两个都是正确的。您可以使用其中任何一个。
我会选择第一个,因为它的代码更少
对于任何方法,您都可以直接使用它们,例如
onChange = (e) => {
}
<Component onChange = {this.onChange} />
在新版本的react中不需要绑定方法

翻阅古今
TA贡献1780条经验 获得超5个赞
您的示例中的差异纯粹是语法上的,而不是功能上的。您可以同时使用这两种效果。
通常,当您要基于某些运行时逻辑(例如,基于传递的props)来计算状态时,可以在构造函数中分配状态。在这种情况下,您将这样编写:
class Example extends Component {
constructor(props) {
this.state = {
fullName: props.firstName + ' ' + props.lastName
}
}
}
添加回答
举报
0/150
提交
取消