【问题标题】:How to dynamically show or hide form fields depending on the state of a BooleanInput field in react-admin?如何根据 react-admin 中的 BooleanInput 字段的状态动态显示或隐藏表单字段?
【发布时间】:2020-05-06 05:43:22
【问题描述】:

我需要用 react-admin 构建一个复杂的编辑表单。该表单具有各种使用 react-admin 的 BooleanInput 组件制作的是/否滑块。 如果用户将滑块设置为“是”,则应动态显示更多表单字段,这些字段在主题上引用滑块。如何查询 BooleanInput 组件的状态,或者这个任务会以不同的方式在 react 中解决吗?

<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" />

【问题讨论】:

    标签: javascript reactjs jsx react-admin


    【解决方案1】:

    我发现:可以像这样使用 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

    【讨论】:

      【解决方案2】:

      你可以在 JSX 中编写动态代码

      > { isShow ? <TextInput ... /> : null }
      

      【讨论】:

      • 我对 react 和 JSX 还是很陌生。我在哪里可以将代码放在 JSX 标签中?
      • 在你的渲染方法的返回内&lt;div&gt; { You can write JavaScript Code Here } &lt;p&gt;Hello&lt;/p &lt;/div&gt;
      • 谢谢,但是 BooleanInput 将它的值存储在哪里?
      • 你有两个选择,(钩子,类)。我会给你一个钩子的例子(你应该阅读它)。 Hooks 让你可以选择将状态保存在功能组件中,s const [boolValue, setBoolValue] = useState(false) &lt;input onChange={ (event) =&gt; setBoolValue(event.target.value) }
      猜你喜欢
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 2010-11-18
      相关资源
      最近更新 更多