【问题标题】:render react const as component将 react const 渲染为组件
【发布时间】:2018-12-08 19:50:28
【问题描述】:

假设我有这个父母

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>
        )
    }
}

【问题讨论】:

    标签: reactjs render es6-class


    【解决方案1】:

    您没有将ParentButton 分配给ChildComponent

    您目前拥有的是一个浮动在构造函数中的const,因为constletvar 关键字是函数/块范围的。

    this. ParentButton = this.props.foo 和简洁的 &lt;this. ParentButton &gt; 在你的渲染函数中会得到你想要的。

    【讨论】:

    • 我将其标记为范围部分的答案。至于渲染 不起作用。 (元素类型无效:应为字符串(用于内置组件)或类/函数(用于复合组件)但得到:对象。)
    • @Yvain 去掉 {} 并像 &lt;this.ParentButton /&gt; 那样渲染它,因为它是一个组件。
    猜你喜欢
    • 2017-09-20
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2018-11-15
    • 2020-12-12
    • 2018-06-16
    • 2020-03-22
    • 1970-01-01
    相关资源
    最近更新 更多