React 新手,我正在测试编写一个小程序,您可以在列表中选择一个名称,然后应该显示一条谚语。事件处理程序handleAuthorClick被调用,setState也被调用,但新文本没有显示。
为什么?
class AuthorList extends React.Component {
constructor(props) {
super(props);
this.state = {
value: -1,
text: "When in Rome do as the Romans",
}
}
handleAuthorClick()
{
let txt = "initial value";
var sel = document.getElementById("author-list");
switch (parseInt(sel.value))
{
case 12 : txt = "When in Rome do as the Romans"; break;
case 33: txt = "If you tell the truth, you don't have to remember anything.";break;
case 256: txt = "History will be kind to me for I intend to write it";break;
default:;
}
this.setState({text: txt});
}
render() {
return (
<div className="author-list">
<h2>Author List</h2>
<select id='author-list' name='author-list' size='15' onClick={() => this.handleAuthorClick()>
<option value="12">Unknown</option>
<option value="33">Mark Twain</option>
<option value="256">Winston Churchill</option>
</select>
<h2>Proverbs</h2>
{this.props.text}
</div>
);
}
}
class ProVerbMain extends React.Component {
render() {
return (
<div className="proverb">
<h1>Dans proverbs</h1>
<div className="author-list">
<AuthorList text = 'Initial value'/>
</div>
</div>
);
}
}
ReactDOM.render(<ProVerbMain />, document.getElementById('root'));
最佳答案
使用 this.state.text
而不是 this.props.text
,因为它是组件的本地状态。当您使用 this.props.text 时,您的组件不知道新渲染的新状态。
您应该在选择选项中使用 onChange()
事件而不是 onClick()
关于javascript - 在 React 中重新渲染类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58607931/