【问题标题】:ReactJS, passing prop from parent to child component?ReactJS,将道具从父组件传递给子组件?
【发布时间】:2018-11-21 01:44:46
【问题描述】:

我有一堆组件需要相同的 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"/>
}

我知道上面的代码不是你应该做的,但是有什么方法可以实现这个功能吗?

【问题讨论】:

  • &lt;Home heading={ () =&gt; &lt;h1&gt;{props.heading}&lt;/h1&gt; }/&gt; ?

标签: javascript reactjs react-props


【解决方案1】:

是的,这是可能的。只需将您的 JSX 组件分配给一个变量并将该变量作为道具传递。你有正确的想法。 例如:

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

您还可以将customHeader 设置为 React 组件,例如:var customHeader = &lt;CustomHeader /&gt;

您可以通过&lt;MyComponent header={customHeader}/&gt; 并在MyComponent 页面的render 函数中,您可以简单地使用{this.props.header} 来加载您的组件。可以对任意数量的组件重复此操作。

基于 cmets 进行编辑。在这种情况下,我会将组件包装在一个函数中。例如:

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

现在,在您的渲染函数中,您可以调用getCustomHeader

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

【讨论】:

  • 我是否需要将{this.props.header} 添加到我需要此自定义标头的每个组件中?
  • 是的。情况差不多,但您不必为每个新标题创建一个新变量(这会破坏整个观点作为您评论的编辑)。您可以将customHeader 传递给多个组件。例如,您可以使用&lt;MyComponent header={customHeader} /&gt;&lt;MyComponent2 header={customHeader} /&gt;
  • 如果每个组件的每个标题都不同怎么办。 ComponentA的标题应该是“标题A”,ComponentB的标题应该是“标题B”等等?
  • 好吧,哇,创建一个函数是如此简单......不知道为什么我没有考虑过。谢谢我接受了你的回答。
  • 没问题,很高兴为您提供帮助!
猜你喜欢
  • 1970-01-01
  • 2021-07-04
  • 2020-11-23
  • 2021-01-16
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多