从外部调用React组件方法

我想从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')
);
JinJin凯梅2020/03/13 15:34:30

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

阿飞宝儿猴子2020/03/13 15:34:30

方法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 15:34:29

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

希望可以帮助任何人:)