本文介绍了在ReactJS中找到已安装组件的findDOMNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在页面中包含两个JS文件,分别为Utility.js和Utility1.js。
Utility.js的代码
I have two JS files included in page as utility.js and utility1.js
Code for 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的代码
Code for 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小提琴,让我知道可能的解决方案。
The problem here is I want focus on input of HelloWorld Component of utility.js from utility1.js. I saw their is one method as findDOMNode for mounted components. But this code is not working for me. Can Somebody try this JS Fiddle here and let me know possible solution.
推荐答案
var HelloWorld = React.createClass({
componentDidMount: function() {
React.findDomNode(this.refs.mytestinput).focus()
},
...
});
或者,如果您的React.js是最新的,请使用以下命令:
or if your React.js is up-to-date, use this:
componentDidMount() {
this.refs.mytestinput.focus()
}
这篇关于在ReactJS中找到已安装组件的findDOMNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!