![](/img/trans.png)
[英]Set value of prop in child component and pass value back to state of app.js, react
[英]Passing a state or prop to pass a value to child component in react
我很新來反應。 我需要將驗證是否成功傳遞給子反應組件。下面是我的父組件。
Login.js - 父級
update = name => {
this.setState({inputValidation:false})// or with es6 this.setState({name})
}
nextClick = () => {
const {type, nicPassportNumber, accountNumner } = this.state;
if(type === ''){ //TODO add validations here
alert('please enter a value to proceed');
this.inputValidation = true;
this.update();
console.log("afetr : ", this.inputValidation);
return;
}
const code = type === 'nic-pass' ? nicPassportNumber : accountNumner;
this.props.verifyNumber(code, type);
};
render() {
const {nicPassportNumber, accountNumner} = this.state;
return (
<div className="container-fluid">
<div className="row form-group">
<div className = "col-lg-10 col-xl-6 offset-xl-3 offset-lg-1">
<Input_Box label = "Enter NIC / Passport" value={nicPassportNumber} onChangeFunc={this.handleChange} valid = {this.state.inputValidation} type='nic-pass' {...this.props}/>
<h2 className="sc-txt-hor-center my-3">OR</h2>
<Input_Box label = "Enter mobile / DTV / Broadband number" value={accountNumner} onChangeFunc={this.handleChange} valid = {this.state.inputValidation} type='account' {...this.props}/>
</div>
</div>
<Footer onBackClick={this.backClick} onNextClick={this.nextClick}/>
</div>
);
Input_Box.js - 子組件
constructor(props) {
super(props);
}
render() {
const {label, value, onChangeFunc, type} = this.props;
console.log("Val input box : ", this.props.inputValidation);
return (
<div className="sc-input">
<label className="sc-input__label mb-3" htmlFor="nic_passport_no">{label}</label>
<input type="text"
className="form-control sc-input__box"
id="nic_passport_no"
placeholder=""
value={value}
onChange={(e) => onChangeFunc(e, type) }/>
<label className="sc-input__error-msg">123214</label>
</div>
);
}
}
我嘗試了 SO 中給出的大部分建議。 但是每次我在子組件中都undefined
inputValidation
時。
我在這里做錯了什么?
這個問題似乎是由傳遞給<Input_Box/>
不正確道具引起的:
{/* use inputValidation prop rather than valid prop */}
<Input_Box inputValidation={this.state.inputValidation} label="Enter NIC / Passport" value={nicPassportNumber} onChangeFunc={this.handleChange} type='nic-pass' {...this.props}/>
<h2 className="sc-txt-hor-center my-3">OR</h2>
{/* use inputValidation prop rather than valid prop */}
<Input_Box inputValidation={this.state.inputValidation} label="Enter mobile / DTV / Broadband number" value={accountNumner} onChangeFunc={this.handleChange} type='account' {...this.props}/>
此外,控制台記錄undefined
的原因似乎是因為您從組件實例this
訪問inputValidation
而不是組件的state
:
// console.log("afetr : ", this.inputValidation);
console.log("after : ", this.state.inputValidation);
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.