【问题标题】:React + Redux: submit multi-component formReact + Redux:提交多组件表单
【发布时间】:2016-11-14 18:17:59
【问题描述】:

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

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

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

在提交按钮组件(记住它与输入组件没有直接关系)中,mapStateToProps 返回 onClick 属性,这是一个可以访问状态和输入值的函数,并且可以执行“不纯”工作(例如 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 文档,它似乎无法绑定两个与上述组件无关的组件(也许我错了;))

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

【问题讨论】:

    标签: javascript forms reactjs redux react-redux


    【解决方案1】:

    在这种情况下不需要使用refs。

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

    您还需要聆听输入的变化。为此,为您的inputonChange 属性提供一个处理程序。然后,此处理程序应更改表单数据,无论是在您的 redux 存储中还是在组件状态中,具体取决于您采用的方法。

    这样,只要它可以访问表单数据,您将提交按钮等放置在您的 react 应用程序中的哪个位置都没有关系。


    对于您的用例的工作示例,have a look at this JSBin。这演示了如何在不依赖 refs 的情况下将表单拆分为多个组件并将输入值保留在 redux 存储中。

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多