从外部调用React组件方法

reactjs React.js

GOL蛋蛋

2020-03-13

我想从React元素的实例中调用React组件公开的方法。

例如,在此jsfiddle中我想alertMessageHelloElement参考中调用该方法

有没有一种方法可以实现而无需编写其他包装程序?

编辑(从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')
);

第1391篇《从外部调用React组件方法》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
JinJin凯梅 2020.03.13

似乎不赞成使用静态方法,而暴露某些函数的其他方法render似乎有些费解。同时,这个关于调试React的Stack Overflow答案虽然看上去有些怪异,但对我来说却很有效。

阿飞宝儿猴子 2020.03.13

方法1 using ChildRef

public childRef: any = React.createRef<Hello>();

public onButtonClick= () => {
    console.log(this.childRef.current); // this will have your child reference
}

<Hello ref = { this.childRef }/>
<button onclick="onButtonClick()">Click me!</button>

方法2: using window register

public onButtonClick= () => {
    console.log(window.yourRef); // this will have your child reference
}

<Hello ref = { (ref) => {window.yourRef = ref} }/>`
<button onclick="onButtonClick()">Click me!</button>
番长神乐小小 2020.03.13

如果您使用的是ES6,则只需在示例中使用“ static”关键字即可,示例如下: static alertMessage: function() { ...
},

希望可以帮助任何人:)

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android