首页 > 解决方案 > How to dynamically show or hide form fields depending on the state of a BooleanInput field in react-admin?

问题描述

I need to build a complex edit form with react-admin. The form has a variety of yes/no sliders made with the BooleanInput component of react-admin. If the user sets the slider to "yes", further form fields should appear dynamically, which refer thematically to the slider. How do I query the status of the BooleanInput component or would this task be solved in react in a different way?

<BooleanInput source="yesno" label="show or hide fields" />
<AutocompleteArrayInput source="probably_hidden1" label="show or hide me" choices={[
        { id: 'one', name: '1' },
        { id: 'two', name: '2' },
        { id: 'three', name: '3' }
]} />
<TextInput multiline source="text" label="show or hide me too" />

标签: javascriptreactjsjsxreact-admin

解决方案


我发现:可以像这样使用 FormDataConsumer 来完成:

<BooleanInput source="yesno" label="show or hide fields" />
<FormDataConsumer>
    {({ formData, ...rest }) => formData.yesno && <div>
        <AutocompleteArrayInput source="yesno" label="show or hide fields" choices={[
            { id: 'one', name: '1' },
            { id: 'two', name: '2' },
            { id: 'three', name: '3' }
        ]} {...rest} />
        <TextInput multiline source="text" label=""show or hide me too" {...rest} />
    </div>
    }
</FormDataConsumer>

请参阅: https ://marmelab.com/react-admin/Inputs.html#hiding-inputs-based-on-other-inputs


推荐阅读