reactjs - 表单在 ReactJs 中是如何工作的?
问题描述
有人可以告诉我表单在 ReactJS 中是如何工作的吗?
当用户单击提交按钮时,我从反应文档中看到的表单下的数据如何显示,关于表单少指导我
例如以非常简单的方式我如何在单击提交按钮时显示数据检查示例。在表单底部显示数据,当输入任何文本然后单击提交按钮然后显示我在表单下方输入文本,我该怎么做?
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
解决方案
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>
)
推荐阅读
- c# - 如何在将excel数据导入listview时使用where子句查询
- regex - 正则表达式仅匹配数字,带逗号和括号的数字但不匹配引号
- ios - UIScrollview 不显示所有内容?
- apache - 在 Apache 代理后面为 S3 静态网站 JS 获取 404
- python - Keras,Tensorflow:预测中的系统偏移
- javascript - 当浏览器不支持功能时,我如何知道是否存在 polyfill 或 Babel 插件?例如:访问器
- ruby-on-rails - Rails 嵌套模型验证仅在填充某些内容时运行
- webforms - 如果页面有两个用户控件引用,则隐藏 Web 表单应用程序中的按钮
- c++ - 使用 #pragma 注释时出现 LNK2019 错误,被 /VERBOSE 输出混淆
- python - 访问和检查对象实例的属性,例如登录页面的“用户”对象中的“用户名”属性