有人可以告诉我表单在ReactJS中如何工作吗?
当用户单击“提交”按钮时,数据如何显示在我从React文档中看到的表单中,关于表单较少指导我
例如,以非常简单的方式,我如何在单击“提交”按钮时显示数据,请检查示例。在表格下方显示数据,当输入任何文本时,单击“提交”按钮,然后向我显示在表格下方输入文本,我该如何这样吗?
import React,{Component} from 'react'
class FormHandling extends Component{
constructor(props){
super(props)
this.state={text:''}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(e){
this.setState({
text:e.target.value
})
}
handleSubmit(e){
e.preventDefault()
// what i can write ther
}
render(){
return(
<div>
<form onSubmit={this.handleSubmit} >
<input type="text" onChange={this.handleChange} value={this.state.text} placeholder="enter name" />
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
export default FormHandling
答案 0 :(得分:0)
handleSubmit(e){
e.preventDefault()
// 1st -> send code to an api
fetch('some_url', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(this.state.text)
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) });
}
}
// 2 -> flag
state = {
text: '',
flag: false
}
handleSubmit = e => {
e.preventDefault();
this.setState({flag: true});
}
...
return(
<div>
<Form onSubmit={this.handleSubmit}/>
{flag && <OtherComp textFromForm={this.state.text} /> }
// or something like this. (if flag is true then render comp)
// I didn't proof this but this is the idea of what you'd do.
</div>
)