[英]React.js How do I get the id in props with the getElementById method?
start to learn React.js recently and encounter the following problem: enter image description here 最近开始学习React.js并遇到以下问题: 在此处输入图片描述
I want to get the div
element using getElementById
but it doesn't work and the console alerts can not read property 'props' of null
. 我想使用
getElementById
获取div
元素,但它不起作用,控制台警报can not read property 'props' of null
。 So how can I get the div
element? 那么如何获取
div
元素呢? it has troubled me for several hours. 它困扰了我几个小时。 Thanks.
谢谢。
The whole idea with React is that you don't access the DOM, but work with a virtual DOM. React的整个想法是您不访问DOM,而是使用虚拟DOM。
To achieve what you are trying to accomplish (which is a little unclear since the code is incomplete), you'll want to use a stateful component that stores user input on this.state
. 为了实现您要完成的任务(由于代码不完整,这有点不清楚),您需要使用一个有状态的组件 ,该组件将用户输入存储在
this.state
。 Check out this page on React forms. 在React表单上查看此页面 。
You'll want to do something like this, where you are tracking user input by storing it on the component: 您将需要执行以下操作,在其中通过将用户输入存储在组件上来跟踪用户输入:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.