ReactJS,将prop从父组件传递到子组件?

时间:2018-11-21 01:44:46

标签: javascript reactjs react-props

我有一堆需要相同道具的组件,并且逐一添加JSX很麻烦,我可以在父级中创建一块JSX并将其作为道具传递给这些子组件吗? / p>

这基本上是我想要做的:

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"/>
}

我知道上面的代码不是您应该如何执行的,但是有什么方法可以实现该功能?

1 个答案:

答案 0 :(得分:2)

是的,那是可能的。只需将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>
}
相关问题