加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 从外部调用React组件方法

发布时间:2020-12-15 06:34:42 所属栏目:百科 来源:网络整理
导读:我想从React元素的实例调用React组件暴露的方法。 例如,在这个jsfiddle https://jsfiddle.net/r6r8cp3z/中,我想从HelloElement引用中调用alertMessage方法。 有没有办法实现这一点,而不必写额外的包装? 编辑(从JSFiddle复制的代码) div id="container"/d
我想从React元素的实例调用React组件暴露的方法。

例如,在这个jsfiddle https://jsfiddle.net/r6r8cp3z/中,我想从HelloElement引用中调用alertMessage方法。

有没有办法实现这一点,而不必写额外的包装?

编辑(从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')
);
访问内部函数有两种方法。一个,像你想要的实例级别,另一个,静态级别。

实例

您需要从React.render返回的函数调用该函数。见下文。

静态的

看看React statics.但是,请注意,静态函数无法访问实例级数据,因此这将是未定义的。

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",{
    name: "World"
});

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

然后做HelloRendered.alertMessage()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读