Redux表单-向FormSection

时间:2019-01-30 14:20:24

标签: reactjs redux-form

我想知道如何动态地向表单节添加名称,而不是像在example中那样具有静态名称。我已经尝试过这样的事情:

class Address extends FormSection {

    render() {
        return <div>
            <Field name="streetName" component="input" type="text"/>
            <Field name="number" component="input" type="text"/>
            <Field name="zipCode" component="input" type="text"/> 
        </div>
    }
}

Address.PropTypes = {
  name: PropTypes.string.isRequired,
};

我正在从连接到redux-form的父组件中调用此组件,如下所示:

  <Address
    name={formSectionName}
  /> 

但是,没有任何东西被渲染,我想用单选按钮切换它,但是组件永远不会被渲染。如何做到这一点,并动态设置FormSection的名称?

1 个答案:

答案 0 :(得分:4)

Javascript中的类继承有些棘手,但是我不想在这里详细介绍。

但是我看到的是上面列出的继承示例,但有一个警告,就是不能更改名称:https://redux-form.com/7.4.2/docs/api/formsection.md/#example-usage

  

“对于地址等很少更改表单节名称的组件,   使组件从FormSection继承可能是有益的   而不是Component,并设置默认名称prop,如下所示。

据我所知,通过继承进行操作,您不再可以使用外部属性来控制它,而是使用静态默认属性...

我对这个例子的个人看法是,老实说,这让我有些困惑。 github上还有一个针对此确切问题的未解决问题:https://github.com/erikras/redux-form/issues/4359

但是为什么不采用这种方法呢?我会通过构图解决它。

class Address extends React.Component {

    render() {

        const { name } = this.props;

        return (
           <FormSection name={name}>
            <div>
              <Field name="streetName" component="input" type="text"/>
              <Field name="number" component="input" type="text"/>
              <Field name="zipCode" component="input" type="text"/> 
            </div>
          </FormSection>
         )
    }
} 
Address.propTypes = {
  name: PropTypes.string.isRequired,
};
相关问题