传递状态或 prop 以将值传递给 react 中的子组件



我对反应很陌生。我需要将验证是否成功传递给子反应组件。下面是我的父组件。

登录.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中给出的大部分建议。但是每次我在子组件中inputValidationundefined时。

我在这里做错了什么?

这个问题似乎是由传递给<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而不是组件的state访问inputValidation

// console.log("afetr : ", this.inputValidation); 
console.log("after : ", this.state.inputValidation);

希望这有帮助!

最新更新