【发布时间】:2017-05-27 21:55:54
【问题描述】:
InputField 和 Button 是自定义组件,它们进入表单以创建表单。我的问题是如何将数据发送回表单,以便在单击按钮时,我可以使用数据(用户名和密码)在表单上触发 ajax:
export default auth.authApi(
class SignUpViaEmail extends Component{
constructor(props){
super(props);
this.state = {
email : "",
password : ""
};
this.storeEmail = this.storeEmail.bind( this );
this.storePassword = this.storePassword.bind( this );
}
storeEmail(e){
this.setState({ email : e.target.value });
}
storePassword(e){
this.setState({ password : e.target.value });
}
handleSignUp(){
this.props.handleSignUp(this.state);
}
render(){
return(
<div className="pageContainer">
<form action="" method="post">
<InputField labelClass = "label"
labelText = "Username"
inputId = "signUp_username"
inputType = "email"
inputPlaceholder = "registered email"
inputClass = "input" />
<Button btnClass = "btnClass"
btnLabel = "Submit"
onClickEvent = { handleSignUp } />
</form>
</div>
);
}
}
);
或者不推荐并且我不应该在表单中创建自定义子组件?
子组件 => InputField
import React,
{ Component } from "react";
export class InputField extends Component{
constructor( props ){
super( props );
this.state = {
value : ""
};
this.onUserInput = this.onUserInput.bind( this );
}
onUserInput( e ){
this.setState({ value : e.target.value });
this.props.storeInParentState({[ this.props.inputType ] : e.target.value });
}
render(){
return <div className = "">
<label htmlFor = {this.props.inputId}
className = {this.props.labelClass}>
{this.props.labelText}
</label>
<input id = {this.props.inputId}
type = {this.props.inputType}
onChange = {this.onUserInput} />
<span className = {this.props.validationClass}>
{ this.props.validationNotice }
</span>
</div>;
}
}
错误:我在父 storeEmail 函数上收到错误 e.target is undefined。
【问题讨论】:
-
您可以将
keyup事件处理程序传递给输入,以便父组件状态始终保持最新。然后,每当调用 handleSignup 时,表单组件就已经拥有它需要的一切。 -
@rufio86 是对的,你需要先更新你的父组件状态。并且你需要绑定
handleSignUp回调,然后你就会得到你的状态。 -
向@rufio86 和 hawk 道歉,请详细说明
标签: javascript forms reactjs input components