Comparing two components - is Component X an instance of Component A

后端 未结 2 893
野性不改
野性不改 2020-12-20 13:31

I have a generic component which maps its child components to filter only children of a certain type, as found below.

However, using the property type w

相关标签:
2条回答
  • 2020-12-20 14:21

    I think your example is correct.

    Indeed, in React 0.12 child.type === Foo.type is the only comparison that works.
    This is related to React 0.12 being in process of deprecating wrapper functions.

    When 0.13 is out, child.type itself will be Foo.

    Nitpick: don't use this.props.children.map, this won't work when there is less than two children.
    Use React.Children.map instead.

    0 讨论(0)
  • 2020-12-20 14:38

    The kind of api you're making is frail and confusing. You shouldn't treat elements as data. If you need to filter, pass data to the component.

    <Main things={[
      {type: 'Foo', element: <Foo />},
      {type: 'Bar', element: <Bar />},
      {type: 'Bar', element: <div>I'm lying but it doesn't matter</div>},
    ]} />
    
    var Main = React.createClass({
        render: function(){
            var filteredChildren = this.props.things.map(function(thing){
                return thing.type === 'Foo' ? thing.element : false;
            });
    
            return <div>{filteredChildren}</div>;
        }
    });
    
    0 讨论(0)
提交回复
热议问题