class App extends React.Component { constructor(props){ // 必须要传递参数 super(props) this.state = { text: this.props.text } } render() { return ( // render不用传props <div>{this.props.children}</div> ) }}constructor和render内部this都指向组件实例,只要constructor内部要读取props就要写明这个参数,但是render不用,为什么呢?
1 回答
噜噜哒
TA贡献1784条经验 获得超7个赞
es6:
There is only one reason when one needs to pass props to super():
When you want to access this.props in constructor.
(Which is probably redundant since you already have a reference to it.)
所以只有在构造器constructor内使用this.props的时候
才写super(props), 不使用传入props也没错.
es5:
React.createClass({
getInitialState(){ return {
text: this.props.text
}
},
render(){ return ...
}
})添加回答
举报
0/150
提交
取消
