[英]How to pass a custom component as a 'prop' to another custom component in React.js render function?
I've written two Reactjs components, one is the form (MainForm) where I will place multiple button components (NextButton). 我已经编写了两个Reactjs组件,一个是表单(MainForm),我将在其中放置多个按钮组件(NextButton)。 When I define the NextButton on the MainForm, I want to specify which component to mount next in the NextButton's handleClick event.
当我在MainForm上定义NextButton时,我想在NextButton的handleClick事件中指定接下来要安装的组件。
Here is the NextButton component: 这是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}/>
);
}
}
Here is the MainForm component: 这是MainForm组件:
class MainForm extends React.Component {
render() {
return (
<div id="formWrapper">
<NextButton value="Custom Code" next= {<NextForm />} />
</div>
);
}
}
In the MainForm component, I am attempting to make a NextButton and pass it the component I want to show when the button is clicked, which is handled by the NextButton handleClick function. 在MainForm组件中,我试图制作一个NextButton,并将单击按钮时要显示的组件传递给它,该按钮由NextButton handleClick函数处理。
I am unable to figure out whether I have a syntax error, or am I just using the wrong approach to accomplish this, can anyone help? 我无法弄清楚是否有语法错误,还是只是使用错误的方法来完成此操作,任何人都可以帮忙吗?
You can't pass it in this way. 您不能以这种方式通过它。 You have to pass it in as a child component.
您必须将其作为子组件传递。
<NextButton value="Custom Code">
<NextForm />
</NextButton>
You can access NextForm inside NextButton with this.props.children
. 您可以使用this.props.children在NextButton中访问
this.props.children
。
You can do something very similar to what you've tried to do, you just need to return valid JSX 您可以执行与尝试执行的操作非常相似的操作,只需要返回有效的JSX
code: https://codesandbox.io/s/q3pxnlo9p6 代码: https : //codesandbox.io/s/q3pxnlo9p6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.