Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

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

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 was a mere guess, and I can't find it documented. Not only that, logging it shows it being a function - which can't be executed. On top of that there's a couple issues that need to be worked around when using Browserify.

Another option would be to read child.prototype.displayName. But that too feels wrong.

Question: Basically, I'm looking for a solid way of comparing whether two ReactJS components are equal.

EXAMPLE

(Updated: not that bad after all)

var Foo = React.createClass({
    render: function() {
        return <div>Foo</div>;
    }
});

var Bar = React.createClass({
    render: function() {
        return <div>Bar</div>;
    }
});

var Main = React.createClass({
    render: function() {
        var filteredChildren = [];

        filteredChildren = React.Children.map(function(child) {
            if (child.type === Foo.type) {
                return child;
            }
        });

        return (
            <div>
                {filteredChildren}
            </div>
        );
    }
});

React.render(<Main><Foo /><Bar /></Main>, document.body);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...