页面中包含两个 JS 文件,分别为 utility.js 和 utility1.js
utility.js 的代码
var HelloWorld = React.createClass({
render: function() {
return (
<p>
Hello, <input type="text" ref="mytestinput" placeholder="Your name here" />!<br />
It is {this.props.date.toTimeString()}
</p>
);
}
});
setInterval(function() {
React.render(
<HelloWorld date={new Date()} />,
document.getElementById('container')
);
}, 1000);
utility1.js 的代码
var MyComponent = React.createClass({
handleClick: function() {
// Explicitly focus the text input using the raw DOM API.
React.findDOMNode(HelloWorld.refs.mytestinput).focus();
},
render: function() {
// The ref attribute adds a reference to the component to
// this.refs when the component is mounted.
return (
<div>
<input type="text" ref="myTextInput" />
<input
type="button"
value="Focus the text input"
onClick={this.handleClick}
/>
</div>
);
}
});
React.render(
<MyComponent />,
document.getElementById('container1')
);
这里的问题是我想关注 utility1.js 中 utility.js 的 HelloWorld 组件的输入。我看到他们是一种用于安装组件的 findDOMNode 方法。但这段代码对我不起作用。有人可以试试这个 JS Fiddle here并让我知道可能的解决方案。
最佳答案
您需要创建全局事件系统才能允许这两个组件 communicate with each other如果他们没有亲子关系。以下是有关 global event system 的更多信息
解决方案如下:jsfiddle
var CustomEvents = (function() {
var _map = {};
return {
subscribe: function(name, cb) {
_map[name] || (_map[name] = []);
_map[name].push(cb);
},
notify: function(name, data) {
if (!_map[name]) {
return;
}
// if you want canceling or anything else, add it in to this cb loop
_map[name].forEach(function(cb) {
cb(data);
});
}
}
})();
关于javascript - ReactJS中已挂载组件的findDOMNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30497163/