渲染react const作为组件

时间:2018-06-29 15:10:35

标签: reactjs render es6-class

假设我有这个父母

const Parent = () => <ChildComponent foo={<Button>clic</Button>} />

为什么此代码有效

class ChildComponent extends React.Component {
    render() {
        return (
            <div>
                {this.props.foo}
            </div>
        )
    }
}

但是此代码不会吗?

class ChildComponent extends React.Component {
    constructor(props) {
        super(props)
        const ParentButton = this.props.foo
    }
    render() {
        return (
            <div>
                <ParentButton />
            </div>
        )
    }
}

我需要类似第二个示例的示例,以便向ParentButton添加一些事件。

我想使this example与类定义的组件一起工作

更新:

基于答案,我现在有了部分解决方案

class ChildComponent extends React.Component {
    constructor(props) {
        super(props)
        this.ParentButton = this.props.foo
    }
    render() {
        return (
            <div>
                {this.ParentButton}
            </div>
        )
    }
}

1 个答案:

答案 0 :(得分:1)

您没有将ParentButton分配给ChildComponent

由于constconstlet关键字是函数/块作用域,因此您目前拥有的是var浮在构造函数中。

this. ParentButton = this.props.foo以及简洁的<this. ParentButton >呈现功能将为您带来帮助。