如何从ReactJS的“外部”访问组件方法?

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


考虑一下代码:


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


冉冉说
浏览 1357回答 3
3回答

繁星coding

如果要从React外部调用组件上的函数,可以在renderComponent的返回值上调用它们:var Child = React.createClass({…});var myChild = React.renderComponent(Child);myChild.someMethod();在React之外获取React Component实例的句柄的唯一方法是存储React.renderComponent的返回值。

慕森王

或者,如果Child上的方法是真正静态的(不是当前道具,状态的乘积),则可以对其进行定义statics,然后像静态类方法一样对其进行访问。例如:var Child = React.createClass({&nbsp; statics: {&nbsp; &nbsp; someMethod: function() {&nbsp; &nbsp; &nbsp; return 'bar';&nbsp; &nbsp; }&nbsp; },&nbsp; // ...});console.log(Child.someMethod()) // bar
打开App,查看更多内容
随时随地看视频慕课网APP