[英]React : get Form values from children component on submit
簡歷:我有一個SignForm
組件,該組件被父組件多次使用,但我SignForm
一種將input values
從SignForm
傳遞給父組件的方法。
我已經搜索過,發現了類似的問題,但就我而言,它不起作用:/
登錄 :調用SignForm的父組件
class Login extends React.Component {
constructor() {
//... code
}
render() {
return (
<SignForm
cta='Go'
switchSign='Create account'
handleSubmit={this._handleSubmit}
/>
)
}
_handleSubmit(username, password) {
console.log(username, password);
this._validateUser(username, password);
}
_validateUser(username, password) {
//....
}
}
SignForm :包含表單標記的子組件
class SignForm extends React.Component {
constructor() {
super();
var self = this;
}
render() {
return (
<form className="Form" onSubmit={this._onSubmit.bind(this)}>
<div className="Form-body">
<p className="InputSide">
<input id="username" type="text" name="username" ref={(input) => this._username = input}/>
<label htmlFor="username">Username</label>
</p>
<p className="InputSide">
<input id="password" type="pass" name="password" ref={(input) => this._password = input}/>
<label htmlFor="password">Password</label>
</p>
</div>
<div className="Form-footer">
<button type="submit" name="sign" className="BtnBasic--lg">{this.props.cta}</button>
<Link to="/login" className="Link">{this.props.switchSign}</Link>
</div>
</form>
)
}
_onSubmit(e) {
e.preventDefault();
console.log(this._username.value, this._password.value); //it logs the input values.
self.props.handleSubmit(this._username.value, this._password.value); //error
}
}
該視圖呈現沒有問題,顯示了傳遞給SignForm的道具。 問題在於表單提交:最后一行self.props.handleSubmit(this._username.value, this._password.value);
返回錯誤:
“未捕獲的TypeError:無法讀取未定義(...)的屬性'handleSubmit'”
謝謝。
如果您的組件內部除了constructor
和Component的生命周期方法( render
, componentWillMount
, componentDidMount
等)之外還有其他函數,並且您將使用this
關鍵字訪問類方法或props
或state
,則需要bind
this
。 您可以在構造函數中執行此操作。
constructor(props) {
super(props);
this._handleSubmit = this._handleSubmit.bind(this);
}
這樣,您不必將其綁定到每個調用者上。
<form onSubmit={this._handleSubmit} />
好的,我找到了解決方案。 這是一個this
和.bind()
缺失:
1.在SignForm
我在此行上替換了self
:
self.props.handleSubmit(this._username.value, this._password.value);
this
:
this.props.handleSubmit(this._username.value, this._password.value);
2.在Login
我添加到此行.bind(this)
:
handleSubmit={this._handleSubmit}
至:
handleSubmit={this._handleSubmit.bind(this)}
結論:我需要更加小心地使用this
和.bind()
。 我希望能幫助可能與我有同樣問題的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.