在不相关的组件之间传递道具 - 反应

时间:2017-03-07 08:14:52

标签: reactjs

我有一个 HeadingComponent ,它在h2标签内显示页面标题,如下所示:

<div id="id1">
      <h2 className="class1">{headingText}</h2>
 </div>

HeadingComponent 位于父div中,其中嵌入了其他组件和div。 ComponentThatDecidesHeading1,ComponentThatDecidesHeading2,ComponentThatDecidesHeading3 是决定{headingText}应该是什么的组件,即

<div id="layoutContentArea">
              <HeadingComponent headingText={headingText}/>
               <div or some wrapper component>
                     <ComponentThatDecidesHeading1/>
                     OR
                     <ComponentThatDecidesHeading2/>
                     OR
                     <ComponentThatDecidesHeading3/>
                  </div>
             </div>

因此,如果呈现了 ComponentThatDecidesHeading1 ,则会生成headingText ='Heading 1',如果呈现 ComponentThatDecidesHeading2 ,则为headingText ='Heading 2',依此类推。

有没有办法放置“if”条件或某些东西来检查哪个组件被渲染并基于该显示相应的headingText? 要么 从,,传递headingText并在中获取。

我检查了ReactJS Two components communicatingPass props to parent component in React.js,但没有得到我的答案。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以创建一个在render()函数中调用的函数,以有条件地渲染所需的组件,同时设置标题文本。我在这里假设您有一个“ComponentThatDecidesHeading”组件,它从其他地方接收不同的道具。如果是这样的话,这样的事情会起作用( EDITED 来回应你的询问):

// Elsewhere in your app:

const propsForMyHeadingComponents = [
{ 
   id: 1,
   headingText: 'HeadingText 1',
   data: [thing1, thing2...]
},
{ 
   id: 2,
   headingText: 'HeadingText 2',
   data: [otherThing1, otherThing2, ...]
},
etc...
];

// Meanwhile, in your parent component:

grabDataAndHeadingText(){
  let headingText;
  let component;

  // Assuming the info you need to load into your components is passed in 
  // from a parent or from a store like Redux:
  const { propsForMyHeadingComponents } = this.props;

  // From there, you can iterate through your array to select the data for the component you want:
  propsForMyHeadingComponents.forEach(thisHeader => {
    if(condition-to-determine-which-component-to-load === thisHeader.id){
      headingText = thisHeader.headingText;
      data = thisHeader.data;
  });
   
  return { data, headingText };
}

render(){

  const { data, headingText } = this.grabDataAndHeadingText();

  // Again, assuming "ComponentThatDecidesHeading" is the same component 
  // with changing props:

  return(
    <div id="layoutContentArea">
      <HeadingComponent headingText={ headingText }/>
        <div or some wrapper component>
            <ComponentThatDecidesHeading data={ data } />
        </div>
    <div>
  );
}

你总能得到&amp;将headingText和组件变量设置为state。

如果您确实拥有100个独立的组件,每个组件都有自己的独特逻辑集等,则可以将组件的名称存储在“propsForMyHeadingComponents”数组中。否则,只需使用您想要渲染它的道具加载组件,如上所述。