我想从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()