ReactJS - Redux Form - 如何根据单选字段元素有条件地显示/隐藏元素?

2024-05-19

我对 Redux 比较陌生,我有一个表单,其中有一些无线电输入“是”或“否”。基本上,我想根据该无线电输入选择有条件地显示包含另一个 redux 表单字段的另一个元素。有直接的方法可以做到这一点吗?

我想检查一下formProps.site_visit值,但我收到一个关于它未定义的错误。作为记录,为了简洁起见,我大大减少了该组件中的代码量。

export class RequestForm extends React.Component {

submit(formProps) {

   const request = {
      square_footage: formProps.get('square_footage'),
      site_visit: formProps.get('site_visit'),
   };

   this.props.dispatch(createRequest(request));
}

// Redux Form Props.
    const { handleSubmit, pristine, reset, submitting } = this.props
    return (
      <form className="page-form__wrapper">
        <div className="page-form__block">
          <div className="page-form__block">
            <p> Is a site visit required to complete this request? </p>
            <Field name="site_visit"
              component={RadioButtonGroup}
            >
              <RadioButton value="true" label="Yes" />
              <RadioButton value="false" label="No" />
            </Field>
          </div>
          {this.formProps.site_visit === true &&
            <div className="page-form__block">
              <p> Estimate the total area of work in square feet </p>
              <Field name="square_footage" component={TextField} hintText="Square Feet" />
            </div>
          }
       </div>
     </form>
   );
}

提前致谢!


你需要使用一个formValueSelector http://redux-form.com/6.5.0/docs/api/FormValueSelector.md/

const selector = formValueSelector('formName');

function mapStateToProps(state, props) {
    const isChecked = selector(state, 'checkboxField');
    return { isChecked };
}

connect using mapStateToProps

渲染方法将如下所示。

render() {
    return (
        { this.props.isChecked && (
            <div>
                this only shows up if the checkboxField Field is checked
            </div>
        ) }
    );
}

edit:

看起来你正在使用reselect- 我从来没有用过createStructuredSelector我并不 100% 理解文档,但可能的解决方案可能是:

const mMapStateToProps = createStructuredSelector({
    request: selectRequestForm(), 
    user: selectUser()
});

const mapStateToProps = (state, props) => {
    return {
        isChecked: selector(state, 'checkboxField'),
        ... mMapStateToProps(state, props) // not sure if createStructuredSelector accepts a props param
    }
};

这将组成两者。我想你也可以使用createSelector with mMapStateToPropsmapStateToProps我原来发帖...

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ReactJS - Redux Form - 如何根据单选字段元素有条件地显示/隐藏元素? 的相关文章

随机推荐