【发布时间】:2017-02-10 21:16:47
【问题描述】:
我正在学习 docs 的反应,但不确定 super() 在此示例中的作用。通常,它不是将传递的参数用于创建一个新实例,然后调用 React.Component 的构造函数方法将这些参数合并到实例中吗?没有任何参数它会做什么?
class LikeButton extends React.Component {
constructor() {
super();
this.state = {
liked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({liked: !this.state.liked});
}
render() {
const text = this.state.liked ? 'liked' : 'haven\'t liked';
return (
<div onClick={this.handleClick}>
You {text} this. Click to toggle.
</div>
);
}
}
ReactDOM.render(
<LikeButton />,
document.getElementById('example')
);
【问题讨论】:
-
super(),在大多数基于类的语言中意味着调用父级的构造函数。所以它会调用 React.Component 的构造函数。
-
超级构造函数是否具有允许零参数有意义的默认参数(隐式或其他)?这个好像可以通过查看源代码来解决。
-
React.Component 构造函数接受一个参数facebook.github.io/react/docs/…
-
我相信这回答了你的问题:stackoverflow.com/a/34995257/1517783
标签: javascript reactjs ecmascript-6 super