我正在教自己用一个超级简单的应用程序做出react,该应用程序要求用户输入 UI 中显示的单词。如果用户输入正确,应用程序会显示另一个单词,依此类推。
我几乎可以正常工作,除了一件事:正确输入单词后,我需要清除输入元素。我在这里看到了几个关于输入元素如何清除自身的答案,但我需要从包含它的组件中清除它,因为这是检查输入的地方......
// the app
class AppComponent extends React.Component {
constructor() {
super();
this.state = {
words: ['alpha', 'bravo', 'charlie'],
index: 0
};
}
renderWordsource() {
const word = this.state.words[this.state.index];
return <WordsourceComponent value={ word } />;
}
renderWordinput() {
return <WordinputComponent id={1} onChange={ this.onChange.bind(this) }/>;
}
onChange(id, value) {
const word = this.state.words[this.state.index];
if (word == value) {
alert('yes');
var nextIndex = (this.state.index == this.state.words.count-1)? 0 : this.state.index+1;
this.setState({ words:this.state.words, index:nextIndex });
}
}
render() {
return (
<div className="index">
<div>{this.renderWordsource()}</div>
<div>{this.renderWordinput()}</div>
</div>
);
}
}
// the input component
class WordinputComponent extends React.Component {
constructor(props) {
this.state = { text:''}
}
handleChange(event) {
var text = event.target.value;
this.props.onChange(this.props.id, text);
}
render() {
return (
<div className="wordinput-component">
<input type="text" onChange={this.handleChange.bind(this)} />
</div>
);
}
}
看到哪里说了alert('yes')
吗?这就是我认为我应该清除 的地方value
,但这没有任何意义,因为它是一个参数,而不是组件的真正状态。我应该让组件将自身传递给更改函数吗?也许那时我可以改变它的状态,但这在设计方面听起来是个坏主意。