【发布时间】:2019-02-09 00:13:07
【问题描述】:
我见过很多代码 sn-ps,例如HelloWorld,其中props 被传递给super()。
当this.props在构造函数中未被访问时,这样做的原因是什么?
class HelloWorld extends Component {
constructor(props) {
super(props);
this.state = { message: 'Hi' };
this.logMessage = this.logMessage.bind(this);
}
logMessage() {
console.log(this.state.message);
}
render() {
return (
<input type="button" value="Log" onClick={this.logMessage} />
);
}
}
【问题讨论】:
-
真的没有理由。如果你没有在构造函数中使用
this.props,你需要做的就是调用super()。Component超类可以很好地设置 props,只是在构造函数中无法访问它们。
标签: javascript reactjs react-native ecmascript-6