我有一堆需要相同 prop 的组件,单独遍历它们来添加 JSX 很麻烦,我可以在父组件中创建一段 JSX 并将其作为 prop 传递给这些子组件吗?
这基本上就是我想做的事情:
function App(props) {
/*not part of the actual code, but I want to
pass this h1 tag into the bottom components as a prop*/
<h1>{props.heading}</h1>
<Home heading="Home"/>
<AboutMe heading="About Me"/>
<Contact heading="Contact"/>
}
我知道上面的代码不是你应该这样做的,但是有没有办法可以实现该功能?
最佳答案
是的,这是可能的。只需将 JSX 组件分配给一个变量并将该变量作为 prop 传递即可。你的想法是正确的。 例如:
var customHeader = <h1>Here's a custom component</h1>
您还可以设置customHeader
到 React 组件,例如:var customHeader = <CustomHeader />
您可以通过<MyComponent header={customHeader}/>
并在您的render
中MyComponent
的功能页面,您可以简单地使用 {this.props.header}
加载您的组件。可以对任意数量的组件重复此操作。
根据评论进行编辑。在这种情况下,我会将组件包装在函数中。例如:
getCustomHeader = (title) => {
return <MyHeader
headerTitle={title}
/>
}
现在,在渲染函数中,您可以调用 getCustomHeader
.
render() {
return <div>
<MyComponent1 header={this.getCustomHeader("Title A")} />
<MyComponent2 header={this.getCustomHeader("Title B")} />
</div>
}
关于javascript - ReactJS,将 prop 从父组件传递给子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53404189/