比较两个组件 - 组件X是组件A的实例 [英] Comparing two components - is Component X an instance of Component A

查看:72
本文介绍了比较两个组件 - 组件X是组件A的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用组件,它将其子组件映射为仅过滤特定类型的子组件,如下所示。

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

但是,使用属性类型只是一个猜测,我找不到记录。不仅如此,记录它表明它是一个功能 - 无法执行。最重要的是,使用Browserify时需要解决几个问题。

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.

另一种选择是阅读child.prototype.displayName。但这也感觉不对。

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

问题:基本上,我正在寻找一种比较两个ReactJS组件是否相等的可靠方法。

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

示例

(更新:毕竟还不错)

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);


推荐答案

我认为你的例子是正确的。

I think your example is correct.

的确,在React 0.12 child.type === Foo.type 是唯一有效的比较。

这与正在处理弃用包装函数的React 0.12有关。

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.

当0.13结束时, child.type 本身将是 Foo

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

Nitpick:不要使用 this.props.children.map 如果少于两个孩子,这将无效。
使用 React.Children.map

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

这篇关于比较两个组件 - 组件X是组件A的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆