【问题标题】:Pass all state values to child component将所有状态值传递给子组件
【发布时间】:2017-03-29 19:16:22
【问题描述】:

我有一个遗留应用程序,它通过 JSON 创建一个多页表单。我正在尝试创建一个通用的多页表单组件,我们可以在其中通过一个 json 来生成一个表单。

应用程序使用buildFormState 将父组件中的state 设置为:

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;
}

这是我对MultiPageForm 组件的调用:

<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)} />

而我在 MultiStepForm 组件中的构造函数是:

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

但它没有正确传递状态,因为有些事情通过了,而有些事情没有。有没有一种方法可以正确传递所有内容而无需在子组件中单独分配?

【问题讨论】:

    标签: javascript json forms reactjs


    【解决方案1】:

    你可以像这样传递所有的状态:

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

    如果您不想拆分它,而是将其作为对象发送:

    <MultiStepForm childState={this.state} />
    

    使用state 字符串作为道具名称应该没有问题,但最好避免使用它。

    【讨论】:

      猜你喜欢
      • 2022-12-04
      • 1970-01-01
      • 2019-01-20
      • 2022-01-18
      • 2019-07-14
      • 2021-01-03
      • 2020-05-18
      • 2019-02-17
      • 2019-04-02
      相关资源
      最近更新 更多