简体   繁体   中英

Pass all state values to child component

I have a legacy application which passes a JSON to create a multi-page form. I'm trying to create a common multi-page form component in which we can just past a json to generate a form.

The application uses a buildFormState which sets the state in the parent component as:

constructor(props) {
  super(props);
  this.state = this.buildFormState();
}

 buildFormState() {
let state = SCREENS.reduce(function(o, s) {
    let _s = s.fields.reduce(function(_o, _f) {
        _o[_f.name] = _f.type == 'checkbox'  ? [] : '';
        return _o;
    }, {});
    return Object.assign(o, _s);
}, {});
state.current_screen = 0;
return state;
}

And this is my call to my MultiPageForm component:

<MultiStepForm SCREENS = {SCREENS} current_screen = {this.state.current_screen} state = {this.state} submitState={this.submitState.bind(this)} uploadPhoto={this.uploadPhoto.bind(this)} completeForm={this.completeForm.bind(this)} />

And my constructor in the MultiStepForm Component is:

constructor(props) {
super(props);
// this.state = this.props;
this.state = this.props.state;
this.SCREENS = this.props.SCREENS
}

But it doesn't pass the state properly as some things get passed while others don't. Is there a way I can pass everything properly without having to individually assign it in the child component?

You can pass all the state like this:

<MultiStepForm {...this.state} />

If you don't want to split it and instead send it as an object:

<MultiStepForm childState={this.state} />

The use of state string as a prop name should not be a problem, still, it is better to avoid it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM