我正在尝试使用ReactJS从文本框中获取输入但不确定如何
import React from 'react'
class component extends React.Component {
constructor() {
super()
this.state = {
word: String('')
}
}
increment() {
this.setState({
word: this.state.word += ''
})
}
render() {
return (
<div>
<p>The message is: { this.state.word } </p>
<input type="text" value={this.state.word} onChange={(event) =>this.handleChange(event.target.value)} />
<input type="submit" value="Add Word" onClick={() => this.increment()} />
{/*<p><input type="button" value="clear msg" onClick={() => this.eraseWord()} /></p>*/}
</div>
)
}
}
文本框中的文本应添加到消息中:
答案 0 :(得分:2)
您需要两个state
个变量,一个将存储textfield
的当前值,另一个将存储完整的值,而increment
方法内附加textfield
值来完成值并再次将其设置为'',试试这个:
class HelloWidget extends React.Component {
constructor() {
super();
this.state = {
word: '',
new: '',
};
}
increment() {
this.setState({
word: this.state.word + this.state.new,
new: '',
})
}
handleChange(value) {
this.setState({
new: value
});
}
render() {
return (
<div>
<p>The message is: { this.state.word } </p>
<input type="text" value={this.state.new} onChange={(e) =>this.handleChange(e.target.value)} />
<input type="submit" value="Add Word" onClick={() => this.increment()} />
</div>
);
}
}
检查jsfiddle
是否有工作示例:https://jsfiddle.net/hse607rr/
答案 1 :(得分:0)
您需要添加handleChange
方法:
class component extends React.Component {
constructor() {
super()
this.state = {
word: ''
};
}
increment() {
this.setState({
word: this.state.word + ''
})
}
handleChange(value) {
this.setState({
word: value
});
}
render() {
return (
<div>
<p>The message is: { this.state.word } </p>
<input type="text" value={this.state.word} onChange={(event) =>this.handleChange(event.target.value)} />
<input type="submit" value="Add Word" onClick={() => this.increment()} />
{/*<p><input type="button" value="clear msg" onClick={() => this.eraseWord()} /></p>*/}
</div>
);
}
}