如何从ReactJS的“外部”访问组件方法? [英] How to access component methods from “outside” in ReactJS?

查看:128
本文介绍了如何从ReactJS的“外部”访问组件方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能从ReactJS的外部访问组件方法?为什么不可能,有什么办法解决呢?

Why can’t I access the component methods from "outside" in ReactJS? Why is it not possible and is there any way to solve it?

考虑以下代码:

var Parent = React.createClass({
    render: function() {
        var child = <Child />;
        return (
            <div>
                {child.someMethod()} // expect "bar", got a "not a function" error.
            </div>
        );
    }
});

var Child = React.createClass({
    render: function() {
        return (
            <div>
                foo
            </div>
        );
    },
    someMethod: function() {
        return 'bar';
    }
});

React.renderComponent(<Parent />, document.body);


推荐答案

React提供了您要尝试执行的操作的界面通过 ref 属性。为组件分配一个 ref ,其 current 属性将成为您的自定义组件:

React provides an interface for what you are trying to do via the ref attribute. Assign a component a ref, and its current attribute will be your custom component:

class Parent extends React.Class {
    constructor(props) {
        this._child = React.createRef();
    }

    componentDidMount() {
        console.log(this._child.current.someMethod()); // Prints 'bar'
    }

    render() {
        return (
            <div>
                <Child ref={this._child} />
            </div>
        );
    }
}

注意:这将仅在子组件被声明为类的情况下才有效,根据此处的文档: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a -class-component

Note: This will only work if the child component is declared as a class, as per documentation found here: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component

更新2019-04-01: 已更改示例以使用类和 createRef 每个最新的React文档。

更新2016-09-19: 已更改示例,根据指南中的每个指南使用ref回调 ref 字符串属性文档。

这篇关于如何从ReactJS的“外部”访问组件方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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