render为什么不用传参

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不用,为什么呢?

人到中年有点甜
浏览 467回答 1
1回答

噜噜哒

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的时候&nbsp;才写super(props), 不使用传入props也没错.es5:React.createClass({ &nbsp;&nbsp;getInitialState(){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;text:&nbsp;this.props.text &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;}, &nbsp;&nbsp;render(){&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;... &nbsp;&nbsp;} })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript