dso*_*l21 9 javascript forms reactjs
我对这个简单的问题感到很难过!我想简单地获取表单数据,验证它,提交它并向Express API提交发布请求.但在此之前,我认为我没有彻底了解如何实现这一目标.我看了看这个问题,这些和一堆人,但我不知道这是最好的办法.
这是我假设将采取的方式:
我为注册页面创建了一个React组件.(简化用于演示)
class SignupForm extends Component {
constructor(props){
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(val){
debugger;
}
render(){
return (
<form onSUbmit={ (e)=> this.onSubmit(e) }>
<input type="text" />
<label></label>
<button type="submit">Submit</button>
</form>
)
}
}
Run Code Online (Sandbox Code Playgroud)
单击按钮时,将触发OnSubmit()函数,在该函数中将传递JSON数据.
{
"name": "Kanye",
"surname": "West",
"email":"yeezy@goodmusic.com",
"password":"notsurehowthiswillwork"
}
Run Code Online (Sandbox Code Playgroud)
在哪里我可以触发我的动作
SignupAction(),这将对我的API进行AJAX调用,然后更新我的reducer.
当使用像react-redux-form或redux- forms这样的库时,混淆成倍增加.我只是想简单有一个模型或东西name,surname email和password,但我觉得这些库,尽快为他们开始有喜欢自己减速过度设计:
const store = createStore(combineForms({
user: initialUser,
}));
Run Code Online (Sandbox Code Playgroud)
我的其他选择是:
class SignupForm extends Component {
constructor(props){
super(props);
this.state.form = {
name : '',
surname: '',
email: '',
password: ''
}
}
onSubmit(e){
e.preventDefault();
this.props.SignupAction(this.state.form);
// then reset the state agian to ''
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我的问题是......这会影响表现,如果是这样的话为什么?
处理表单非常简单:
class UserInfo extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const formData = {};
for (const field in this.refs) {
formData[field] = this.refs[field].value;
}
console.log('-->', formData);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input ref="phone" className="phone" type='tel' name="phone"/>
<input ref="email" className="email" type='tel' name="email"/>
<input type="submit" value="Submit"/>
</form>
</div>
);
}
}
export default UserInfo;Run Code Online (Sandbox Code Playgroud)
我建议使用redux-form.它为您提供以下选项:
但如果仍然不想使用(我强烈建议使用它),你可以做的是在表单提交只是验证你的数据并在你的容器中发送一个动作.因此,将您的数据作为参数从组件传递到容器,您可以在其中发送操作调用post/put API(以redux形式,您不需要传递任何内容,您可以直接从商店中读取).
onSubmit(val){
debugger;
}
render(){
const { onSubmit } = this.props //pass onSubmit from
return (
<form onSubmit={ (e)=> {onSubmit} ) }>
<input type="text" />
<label></label>
<button type="submit">Submit</button>
</form>
)
}
}
Run Code Online (Sandbox Code Playgroud)
容器:
mapDispatchToProps(dispatch){
return {
onSubmit => {
//dispatch action
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23043 次 |
| 最近记录: |