我想接受输入字段中输入的内容,并在用户单击“提交”后将其显示在屏幕上。我知道这似乎很基础,但是我是React的新手。提前谢谢!
import React, { Component } from 'react';
class TextInput extends Component {
constructor(props){
super(props);
this.state = { info: "", showName: false };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(evt) {
evt.preventDefault();
this.setState({ info: evt.target.value })
}
handleSubmit(evt){
evt.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.info}
onChange={this.handleChange}/>
<button>Submit</button>
</form>
//text from input appears here
</div>
);
}
}
export default TextInput;
答案 0 :(得分:2)
如果我的理解正确,您只想在用户单击提交后显示文本。在这种情况下,您可以使用handleSubmit在状态submittedInfo
中设置一个特殊值,然后显示该值。
import React, { Component } from 'react';
class TextInput extends Component {
constructor(props){
super(props);
this.state = { info: "", submittedInfo: "", showName: false };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(evt) {
evt.preventDefault();
this.setState({ info: evt.target.value })
}
handleSubmit(evt){
evt.preventDefault();
this.setState({submittedInfo: this.state.info})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.info}
onChange={this.handleChange}/>
<button>Submit</button>
</form>
//text from input appears here
<div>{this.state.submittedInfo}</div>
</div>
);
}
}
export default TextInput;
另一种方法可能是将布尔值isSubmitted
存储在状态中,指示用户是否已提交表单,然后如果this.state.info
为{{1},则显示isSubmitted
}
答案 1 :(得分:0)
您已经具有类似状态
this.state = { info: "", showName: false };
您可以使用showName
状态显示文本,
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.info}
onChange={this.handleChange}/>
<button>Submit</button>
</form>
//text from input appears here
{this.state.showName && <div>{this.state.info}</div>}
</div>
);
您的handleSubmit
函数应该是
handleSubmit(evt){
evt.preventDefault();
this.setState({showName:true})
}