【问题标题】:ReactJS - Accessing Methods of Children (without using refs)ReactJS - 访问子项的方法(不使用 refs)
【发布时间】:2015-12-17 01:52:57
【问题描述】:

我正在尝试访问父组件中子组件的方法。

首先我想使用 refs 而不是 this.props.children,但是只有在我的组件中使用它们时才能访问 refs。

用这个的时候,好像不行:

<Parent>
   <Child ref="testChild" />
</Parent>

在我的父组件中,我无法访问 this.refs.testChild - 因此我必须使用 this.props.children 访问此组件。

但是:当使用this.props.children 访问它们时,我无法调用孩子的方法。

例子:

// Child.jsx

{
  customMethod() {},
  render() {... some stuff ...}
}

// Parent.jsx

{
   callChildrenMethods() {
       this.props.children.map((child)=>{
           console.log(child.props); // Props Object
           console.log(child.customMethod); // Undefined
       });
   },
   render() {return(<div>{this.props.children}</div>)}
}

如您所见:customMethod 未定义。有什么简单的方法可以访问这些方法吗?更好的方法是使用refs 访问孩子,但在我的情况下这是不可能的。

【问题讨论】:

  • 你想通过从父母传递道具到孩子或使用商店来实现这是不可能的?

标签: reactjs


【解决方案1】:

this.props.children 是不透明的,您应该使用React.Children API 进行迭代。无论如何,这是一个使用一些hackery来调用子方法的小提琴 - https://jsfiddle.net/sukantgujar/4bffu7tw/3/ 基本上你需要访问指向被包装组件实例的子类型对象。

var child = React.Children.only(this.props.children),
childType = child.type,
childProto = child.type.prototype,
childName = childProto.constructor.displayName,
childMethod = childProto.someMethod;

【讨论】:

  • 我现在正在使用您的解决方案,它的工作方式就像我需要的那样。
  • 您还需要添加类型检查以确保您只在正确的孩子上调用方法。
  • 是的 - 我这样做是通过比较 displayName。
【解决方案2】:

你应该通过道具让孩子知道:

var Child = React.createClass({
    render: function() {

        if(this.props.shouldRunChildrensMethod) {
            this.childsMethod();
        }

        return (...);
    }
});

var Parent = React.createClass({

    getInitialState: function() {
        return {
            shouldRunChildrensMethod: false
        }
    },

    callChildrenMethods: function() {

        this.setState({
            shouldRunChildrensMethod: true
        });
    },

    render: function() {
        return (
            <Child shouldRunChildrensMethod={this.state.shouldRunChildrensMethod} />
        );
    }

});

您还可以查看2路绑定:

https://facebook.github.io/react/tips/communicate-between-components.html

虽然这种沟通将是一对一地与每个孩子与父母单独进行的。

【讨论】:

  • 在你的情况下,我必须在渲染方法中添加孩子——但我不想。孩子应该由开发人员添加到他想要的视图中。但也许可以通过 this.props.children 添加道具(我可以访问它们,所以也可以操纵它们)......我会试一试。谢谢提示
  • @TimoRütten 实际上,我建议您的方式是 Facebook 建议解决此问题的方式,但您可以看到更新的答案更多其他选项
  • 但是当以我在上面的示例中所做的方式使用父母和孩子时,访问它们的典型方法就像另一个答案所示 - 对吗?因为正如我所见,使用您的解决方案不可能像这样访问它们
猜你喜欢
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 2019-07-21
  • 2015-05-25
  • 2019-12-15
相关资源
最近更新 更多