我是 React js 的新手,我需要让另一个类访问组件的状态,我遇到了这个问题,因为我使用的是原子设计,因为在一个组件中编写所有内容都变成了一个问题,这里是我的代码: Headcomponent:
class Headcomponent extends React.Component{
constructor (props) {
super(props);
this.state = {
email: '',
password: '',
formErrors: {email: '', password: ''},
emailValid: false,
passwordValid: false,
formValid: false,
items: [],
}
}
this.setState({formErrors: fieldValidationErrors,
emailValid: emailValid,
passwordValid: passwordValid
}, this.validateForm);
}
validateForm() {
this.setState({formValid: this.state.emailValid &&
this.state.passwordValid});
}
render(){
return (
<Form fields={this.props.form} buttonText="Submit" />
);
}
}
Headcomponent.propTypes = {
form: PropTypes.array,
};
Headcomponent.defaultProps = {
form: [
{
label: 'label1',
placeholder: 'Input 1',
},
{
label: 'label2',
placeholder: 'Placeholder for Input 2',
},
],
};
export default Headcomponent;
表单.js
const Form = props => (
<form className="Form">
{
props.fields.map((field, i) => (<LabeledInput label={field.label} placeholder={field.placeholder} key={i}/>))
}
<Button text={props.buttonText} />
</form>
);
Form.propTypes = {
fields: PropTypes.arrayOf(PropTypes.object).isRequired,
buttonText: PropTypes.string.isRequired,
};
export default Form;
LabeledInput.js(我需要在这里传递我的密码状态)
const LabeledInput = props => (
<div className={`form-group `} >
<Label text={props.label} />
<Input value={props.value} placeholder={props.placeholder} type="text" onChange={props.onChange} />
<div class="valid-feedback">{props.errorMessage}</div>
<small class="form-text text-muted">{props.exampleText}</small>
</div>
);
LabeledInput.propTypes = {
label: PropTypes.string.isRequired,
placeholder: PropTypes.string,
onChange: PropTypes.func.required,
value: PropTypes.string.isRequired,
exampleText: PropTypes.string,
errorMessage: PropTypes.string,
};
export default LabeledInput;
如何访问 headComponent 中的状态LabeledInput
?