我通过一个名为 renderToday()
的函数渲染了日期。我想要获取日期的原因是我可以从该日期向左或向右移动。我需要相应地更改日期。
renderToday: function() {
var today = new Date();
return today.toDateString();
},
我尝试使用 document.getElementById('date')
,并将 div
设置为 id“date”,并使用 .innerHTML
。现在 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>
);
}
});
最佳答案
发生这种情况是因为当 DOM
尚未准备好时,您试图及时从 DOM
获取元素,您只需调用 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>;
}
});
您可以在 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>;
}
});
关于javascript - document.getElementById().innerHTML 未在 ReactJS 中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33525529/