为了账号安全,请及时绑定邮箱和手机立即绑定

render为什么不用传参

render为什么不用传参

人到中年有点甜 2018-10-12 14:15:13
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 ...
  }
})


查看完整回答
反对 回复 2018-11-24
  • 1 回答
  • 0 关注
  • 466 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号