0

目前我有以下

methodName = () => {
  const {
    collectionOfComponents
    ...
    ...
  } = this.props;

  return (
    <Wrapper1>
      {collectionOfComponents.map((oneComponent, index) => (
        <Wrapper2
          ..props
        >
          {oneComponent.component}
        </Wrapper2>
      )}
    </Wrapper1>
  );
};

对于collectionOfComponents,我传递了以下内容

collectionOfComponents={[
<ComponentOne prop1... prop2... />,
<ComponentOne prop1... prop2... />,
<ComponentTwo prop1... prop2... />
]}

有没有办法确定何时ComponentTwo通过,以便我可以执行不同的渲染。我不知道该怎么做

编辑对不起,应该说清楚,但我不想改变地图中的渲染方法我正在寻找一个单独的函数来首先检查componentTwo数组中是否存在,然后(也许)使用第三个调用两个方法之一,这将是两个不同的返回方法。然后我将在 render 方法中调用该函数

4

4 回答 4

1

当你使用一个组件时,React 会创建一个Element。每个元素都有一个type属性。类型是组件元素的函数类,或DOM 元素的字符串('button')。

要查找创建元素的组件,请将元素的类型与创建它的类的函数进行比较:

const ComponentOne = () => 1;
const ComponentTwo = () => 2;
class ComponentThree extends React.Component {
  render() {
    return 3;
  }
}

const Wrapper = ({ children }) => (
  <div>
  {React.Children.map(children, (El) => {
    switch(El.type) {
      case ComponentOne:
        return <div className="red">{El}</div>;
      case ComponentTwo:
        return <div className="blue">{El}</div>;
      case ComponentThree:
        return <div className="green">{El}</div>;
    }
    
    return null;
  })}
  </div>
);

ReactDOM.render(
  <Wrapper>
    <ComponentOne />
    <ComponentOne />
    <ComponentTwo />
    <ComponentThree />
  </Wrapper>,
  demo
);
.red { background: red; }
.blue { background: blue; }
.green { background: green; }
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="demo"></div>

于 2018-11-12T21:40:38.197 回答
0
const isComponentTwo = collectionOfComponents.some(component => component.type.displayName.includes('ComponentTwo'));

如果 collectionOfComponents 中至少有一个组件是 ,则上述内容将返回 true ComponentTwo

然而,这是不可取的。永远不要使用 using displayNameor用于生产。type这是因为,例如,在缩小过程中,displayNameandtype会发生变化,因此您期望的逻辑不会以您期望的方式发生。

以下状态

displayName 字符串用于调试消息。通常,您不需要显式设置它,因为它是从定义组件的函数或类的名称推断出来的。如果您想显示不同的名称以进行调试或创建高阶组件时,您可能需要显式设置它

flagProp更好的解决方案是向您的组件添加某种类型。例如

decideWhatToDo = () => {
  const { flagPropName } = this.props;
  return flagPropName
    ? this.methodOne()
    : this.methodTwo();
 }

在这两种方法中,您可以决定如果componentTwo存在或不存在要做什么

于 2018-11-13T20:46:35.783 回答
-1

使用 indexOf 签入数组:

collectionOfComponents.indexOf('ComponentTwo') !== -1 // found
于 2018-11-12T21:15:19.510 回答
-1

也许您可以使用这种方式或类似方式?

    <Wrapper1>
      {collectionOfComponents.map((oneComponent, index) => (
        <Wrapper2
          ..props
        >
          {oneComponent.component instanceof ComponentTwo ? renderWasYouWant : otherRender }
        </Wrapper2>
      )
    </Wrapper1>
于 2018-11-12T21:47:52.430 回答