React + Redux:提交多组件表单

时间:2016-07-12 13:16:33

标签: javascript forms reactjs redux react-redux

假设我有包含输入字段的组件A. 第二个组件B包含一个提交按钮。 这两个组件没有直接链接(例如,它们是2个深度树中的2个叶子)

On Submit我需要检索输入值,如何在react + redux环境中解决这个问题?

我想到的最明显的解决方案是将React Component的refs绑定到redux状态, 以这种方式,状态具有对输入值的引用(通过state.fieldName.input.value访问)。

在提交按钮组件中(记住它与输入组件没有直接关系)mapStateToProps返回onClick prop,它是一个可以访问状态的函数,因此可以访问输入值并可以执行“不纯”工作(例如db请求)

所以我的代码应该是这样的:

//components/TestForm.jsx
class TestForm extends Component {
    render() {
        return  <FormInput 
                    ref={(ref) => this.props.registerFormField(ref)} 
                    value=...
                    ...
                />
    }
}

//redux/actions/index.js
const registerFormField = (field) => {
  return {
    type: ActionTypes.REGISTER_FORM_FIELD,
    field: field
  }
}

//redux/reducers/index.js
const rootReducer = (state = {}, action) => {
  switch (action.type) {
    case ActionTypes.REGISTER_FORM_FIELD:
        var newState = {...state};
        newState[action.field.input.name] = action.field.input;
      return newState
    default:
      return state

  }
}

//containers/SubmitButton.js
const mapStateToProps = (state, ownProps) => {
    return {
        text: "Submit",
        onClick: () => {
            //do your impure job with state.fieldName.value
        }
    }
}
const SubmitButton = connect(
  mapStateToProps,
  mapDispatchToProps
)(FormSubmitButton)

//components/FormSubmitButton.jsx
class FormSubmitButton extends Component {
    render() {
        return  <button 
                    onClick={this.props.onClick}
                >
                    {this.props.text}
                </button>
    }
}

我简要阅读了redux-form docs,它似乎无法绑定两个不相关的组件,如上所述(也许我错了;)

有没有其他正确/优雅的解决方案来解决这个问题?

1 个答案:

答案 0 :(得分:1)

在这种情况下无需使用ref

惯用法是通过提供value属性将表单字段创建为controlled components。这可以从全局状态(映射在mapStateToProps中)提供,也可以从公共父组件的状态提供。

您还需要收听输入的更改。为此,请为onChange的{​​{1}}道具提供处理程序。然后,此处理程序应在您的redux存储或组件状态中更改表单数据,具体取决于您采用的方法。

这样,只要它可以访问表单数据,在您的响应应用程序中放置提交按钮等的位置无关紧要。

有关您的用例的工作示例,have a look at this JSBin。这演示了如何将表单分成多个组件,并将输入值保留在redux存储中,而不依赖于input

相关问题