如何将自定义组件作为“prop”传递给React.js渲染函数中的另一个自定义组件?

时间:2018-01-24 01:32:24

标签: javascript reactjs

我写了两个Reactjs组件,一个是表单(MainForm),我将放置多个按钮组件(NextButton)。当我在MainForm上定义NextButton时,我想在NextButton的handleClick事件中指定下一个要挂载的组件。

以下是NextButton组件:

class NextButton extends React.Component {

    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(event){
        ReactDOM.unmountComponentAtNode(parentElement);
        ReactDOM.render(
            this.props.next,
            parentElement
        );
    }

    render() {
        return (
            <input type="button" onClick={this.handleClick} value={this.props.value}/>
        );
    }
}

以下是MainForm组件:

class MainForm extends React.Component {

    render() {
        return (
            <div id="formWrapper">
                <NextButton value="Custom Code" next= {<NextForm />} />
            </div>
        );
    }
}

在MainForm组件中,我尝试创建一个NextButton并将单击按钮时要显示的组件传递给它,该按钮由NextButton handleClick函数处理。

我无法弄清楚我是否有语法错误,或者我只是使用错误的方法来完成此操作,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

你不能以这种方式传递它。您必须将其作为子组件传递。

<NextButton value="Custom Code">
   <NextForm />
</NextButton>

您可以使用this.props.children访问NextButton中的NextForm。

答案 1 :(得分:0)

你可以做一些与你试图做的非常类似的事情,你只需要返回有效的JSX

代码:https://codesandbox.io/s/q3pxnlo9p6

相关问题