简体   繁体   English

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

[英]ReactJS, passing prop from parent to child component?

I have a bunch of components that require the same prop, and going through them individually to add the JSX is cumbersome, can I create a piece of JSX in the parent that will be passed to these child components as a prop? 我有一堆需要相同道具的组件,并且逐一添加JSX很麻烦,我可以在父级中创建一块JSX并将其作为道具传递给这些子组件吗?

Here's basically what I want to do: 这基本上是我想做的:

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

I know the code above isn't how you're supposed to do it, but is there a way I can accomplish that functionality? 我知道上面的代码不是您应该怎么做,但是有没有办法我可以完成该功能?

Yes, that's possible. 是的,那是可能的。 Just assign your JSX component to a variable and pass that variable as a prop. 只需将JSX组件分配给一个变量,然后将该变量作为prop传递即可。 You have the right idea. 你有正确的主意。 For example: 例如:

var customHeader = <h1>Here's a custom component</h1>

You can also set customHeader to a React component such as: var customHeader = <CustomHeader /> 您也可以将customHeader设置为React组件,例如: var customHeader = <CustomHeader />

You can pass through <MyComponent header={customHeader}/> and in your render function of MyComponent page, you can simply use {this.props.header} to load your component. 您可以通过<MyComponent header={customHeader}/>进行传递,并在MyComponent页面的render函数中,只需使用{this.props.header}即可加载组件。 This can be repeated for any number of components. 可以对任意数量的组件重复此操作。

Edit based on comments. 根据评论进行编辑。 In that case, I would wrap the component in a function. 在那种情况下,我会将组件包装在一个函数中。 For example: 例如:

getCustomHeader = (title) => {
    return <MyHeader
        headerTitle={title}
    />
}

Now, in your render function, you can call getCustomHeader . 现在,在渲染函数中,可以调用getCustomHeader

render() {
    return <div>
        <MyComponent1 header={this.getCustomHeader("Title A")} />
        <MyComponent2 header={this.getCustomHeader("Title B")} />
    </div>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM