从外部调用 React 组件方法 [英] Call a React component method from outside

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

问题描述

我想从 React Element 的实例调用一个由 React 组件公开的方法.

I want to call a method exposed by a React component from the instance of a React Element.

例如,在这个 jsfiddle 中.我想从 HelloElement 引用中调用 alertMessage 方法.

For example, in this jsfiddle. I want to call the alertMessage method from the HelloElement reference.

有没有一种无需编写额外包装器就可以实现这一目标的方法?

Is there a way to achieve this without having to write additional wrappers?

编辑(从 JSFiddle 复制代码)

Edit (copied code from JSFiddle)

<div id="container"></div>
<button onclick="onButtonClick()">Click me!</button>

var onButtonClick = function () {

    //call alertMessage method from the reference of a React Element! Something like HelloElement.alertMessage()
    console.log("clicked!");
}

var Hello = React.createClass({displayName: 'Hello',

    alertMessage: function() {
        alert(this.props.name);                             
    },

    render: function() {
        return React.createElement("div", null, "Hello ", this.props.name);
    }
});

var HelloElement = React.createElement(Hello, {name: "World"});

React.render(
    HelloElement,
    document.getElementById('container')
);

推荐答案

有两种方法可以访问内部函数.一个是实例级别,如您所愿,另一个是静态级别.

There are two ways to access an inner function. One, instance-level, like you want, another, static level.

您需要在 React.render 返回时调用该函数.见下文.

You need to call the function on the return from React.render. See below.

看看 ReactJS 静态.但是请注意,静态函数无法访问实例级数据,因此 this 将是 undefined.

Take a look at ReactJS Statics. Note, however, that a static function cannot access instance-level data, so this would be undefined.

var onButtonClick = function () {
    //call alertMessage method from the reference of a React Element! 
    HelloRendered.alertMessage();
    //call static alertMessage method from the reference of a React Class! 
    Hello.alertMessage();
    console.log("clicked!");
}

var Hello = React.createClass({
    displayName: 'Hello',
    statics: {
        alertMessage: function () {
            alert('static message');
        }
    },
    alertMessage: function () {
        alert(this.props.name);
    },

    render: function () {
        return React.createElement("div", null, "Hello ", this.props.name);
    }
});

var HelloElement = React.createElement(Hello, {
    name: "World"
});

var HelloRendered = React.render(HelloElement, document.getElementById('container'));

然后执行HelloRendered.alertMessage().

这篇关于从外部调用 React 组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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