React:如何访问this.props.children中的refs [英] React: How to access refs in this.props.children

查看:735
本文介绍了React:如何访问this.props.children中的refs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用子组件的函数。

是否有可能从React中的this.props.children获取引用。

I want to call a function of a child component.
Is there a possibility to get refs from this.props.children in React.

var ComponentSection = React.createClass({

    componentDidMount: function() {
      // How to access refs in this.props.children ?
      this.refs.inner.refs.specificPanel.resize();
    },

    render: function () {
        return (
          <div className="component-section" ref="inner">
            {this.props.children}
          </div>
        );
    }
});

var Panel = React.createClass({

    resize: function() {
        console.log('Panel resizing');
    },

    render: function () {
        return (
          <div className="Panel">
            Lorem   ipsum dolor sit amet 
          </div>
        );
    }
});

var MainComponent = React.createClass({
    render: function () {
        return (
           <ComponentSection>
            <Panel ref="specificPanel"></Panel>
           </ComponentSection>
        );
    }
});

ReactDOM.render(
  <MainComponent></MainComponent>,
  document.getElementById('container')
);

我做了一个小小的演示: https://jsfiddle.net/69z2wepo/26929/

I made a little demo: https://jsfiddle.net/69z2wepo/26929/

提前致谢

推荐答案

参考React是组件与其 所有者 而您想要的是元素与其父级之间的关系。父子关系是不透明的,父级只接收渲染中的子元素,永远不会访问已解析的组件

Ref in React is a relationship between a component and its owner while what you want is a relationship between an element and its parent. A parent-child relationship is opaque, the parent only receives the child elements on render and never gets access to the resolved components.

在您的情况下, ref =specificPanel建立从 MainComponent 到<的链接code>面板。如果你想从 ComponentSection 调用 Panel 的方法,它应该拥有面板 s而不是作为孩子接收它们。

In your case, the ref="specificPanel" establishes a link from the MainComponent to the Panel. If you want to call methods of Panel from ComponentSection, it should own the Panels instead of receiving them as children.

您可以随时获得的创意> React.Children.map React.createElement (手工克隆元素,从而从原始所有者那里窃取它们),但这会带来一些严重的潜在缺陷。更好的方法可能是重新考虑组件树的所有权结构。

You could always get creative with React.Children.map and React.createElement (cloning the elements by hand and thus stealing them from the original owner), but this introduces some serious potential pitfalls. A better approach would likely be re-thinking the ownership structure of your component tree.

这篇关于React:如何访问this.props.children中的refs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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