【问题标题】:How to get information from children如何从孩子那里获取信息
【发布时间】:2014-11-18 05:38:22
【问题描述】:

我对 reactjs 很陌生(实际上是三天)。我想构建一个组件,该组件根据策略(由组件实现)和某些子属性来布置其子级。一些属性在创建时作为道具直接传递给孩子;其他一些属性,例如它的尺寸,是每个孩子固有的。也就是说,这个 Layout 组件将像这样使用:

<Layout>
    <Child1 propx=... propy=...>...</Child1>
    <Child2 propz=...>...</Child2>
    ...
</Layout>

孩子的位置将取决于 propx、propy、propz、... 和孩子的大小。

好吧,布局组件需要知道其子道具的值及其大小。起初,我给子类一个方法 'getProperties' 来返回相关属性,我在 React.Children.forEach(this.props.children, fn) 中调用了该方法,但我发现传递给 fn 的对象不是组件实例,所以我不能在它上面调用 getProperties。然后,我尝试向每个 Layout 子级传递一个额外的属性“uploadProperties”,并由子级调用一个回调来告诉 Layout 它需要知道什么。我知道我不能在孩子中调用 setProps,所以我想出了这个:

var Layout = React.createClass({
    storeChildProperties: function (properties) {
        this.childData = this.childData || [];
        this.childData.push(properties);
    },
    render: function () {
        var self = this;
        var children = [];
        React.Children.forEach(this.props.children, function (child) {
            var clone = React.addons.cloneWithProps(
                child,
                {key: child.props.key, uploadProperties: self.storeChildProperties});
            children.push(clone);
        });
        this.props.children = children;
        return <div>{this.props.children}</div>;
    }
}

它似乎有效,但我对两件事感到不安。首先,我不喜欢将 'childData' 附加到 Layout 实例(我不知道该放在哪里)。二、不知道替换this.props.children是否可以。实际上,即使我不这样做也可以,我只是

return <div>{children}</div>;

无论如何,这是从儿童那里获取信息的合理方式吗?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您可以通过this.props.children[0].props访问儿童道具。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      相关资源
      最近更新 更多