[英]document.getElementById().innerHTML not getting text in ReactJS
I rendered the date via a function called renderToday()
. 我通过一个名为
renderToday()
的函数渲染了日期。 The reason I want to get the date, is so I can go left, or right from that date. 我想获取日期的原因是,我可以从该日期左移或右移。 And I need to change the date accordingly.
我需要相应地更改日期。
renderToday: function() {
var today = new Date();
return today.toDateString();
},
I tried using document.getElementById('date')
, and I set the div
with an id of "date", and I used .innerHTML
. 我尝试使用
document.getElementById('date')
,并将div
的ID设置为“ date”,然后使用.innerHTML
。 Now everything below AccountsUIWrapper, doesn't show up now. 现在,AccountsUIWrapper下的所有内容现在都不会显示。
renderMoods() {
// Get tasks from this.data.moods
var d = document.getElementById("date");
return (<div>{d.innerHTML}</div>);
},
render: function() {
return (
<div className="container">
<h1>How are You?</h1>
<AccountsUIWrapper />
{ this.data.currentUser ?
<div>
<form className="your_mood" onSubmit={this.handleSubmit} >
<select ref="mood">
<option value="0" disabled selected>Select your Mood</option>
<option value=":)">:)</option>
<option value=":|">:|</option>
<option value=":(">:(</option>
</select>
<button type="submit">submit</button>
</form>
<div id="date">
{this.renderToday()}
</div>
<div>
{this.renderMoods()}
</div>
</div>
: ''
}
</div>
);
}
});
It happens because you are trying get element from DOM
in time when DOM
is not ready, you can just call renderToday()
in renderMoods()
发生这种情况是因为您试图在
DOM
尚未准备就绪时及时从DOM
中获取元素,您可以只在renderMoods()
调用renderToday()
renderMoods()
var Component = React.createClass({
renderToday() {
return Date.now();
},
renderMoods() {
return <h2>
{ this.renderToday() }
</h2>;
},
render() {
return <div>
<h1>Component</h1>
<div>{ this.renderToday() }</div>
<div>{ this.renderMoods() }</div>
</div>;
}
});
you can call DOM
operations in componentDidMount
handler, read more about component lifecycle
- it is possible but not recommended 您可以在
componentDidMount
处理程序中调用DOM
操作,了解有关component lifecycle
更多信息- 可能但不建议
var Component = React.createClass({
renderToday() {
return Date.now();
},
componentDidMount() {
document.getElementById('mood').innerHTML = document.getElementById('date').innerHTML
},
render() {
return <div>
<h1>Component</h1>
<div id="date">{ this.renderToday() }</div>
<div id="mood"></div>
</div>;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.