【问题标题】:Accessing the value of sibling fields on a react-final-form component访问 react-final-form 组件上同级字段的值
【发布时间】:2018-02-07 02:16:18
【问题描述】:

我在 react-final-form 表单上有两个选择字段。选择字段有一个“选项”列表以显示在下拉列表中。 我想做的是确保第二个下拉列表中可用的选项被第一个下拉列表中选择的项目“减少”。

因此,这需要第二个下拉菜单知道在第一个下拉菜单中选择了什么值。这是我想要实现的概念:

const fruitOptions = ['apple', 'orange', 'banana', 'grapes'];
<Field
  name = "morningTea"
  component = {SelectField}
  label = "Fruit for Morning Tea"
  options = {fruitOptions}
/>
<Field
  name = "afternoonTea"
  component = {SelectField}
  label = "Fruit for Afternoon Tea"
  options = {_.without(fruitOptions, morningTea)}
/>

但我看不到访问表单上其他字段值的方法。鉴于“fruitOptions”列表不是它自己的字段。

【问题讨论】:

    标签: react-final-form final-form


    【解决方案1】:

    好吧,这在我看来像是一个文档问题 - 我会提出一张票。

    基本上文档只是缺少FormRenderProps 类型也有一个“值”属性。从这里,在由 react-final-form 修饰的组件中,您可以访问 props.values,并将值从那里传递给其他组件/字段。

    例如

    <Form
        render={formRenderProps => {
            const { morningTea } = formRenderProps.values;    
            const fruitOptions = ['apple', 'orange', 'banana', 'grapes'];
            <Field
              name = "morningTea"
              component = {SelectField}
              label = "Fruit for Morning Tea"
              options = {fruitOptions}
            />
            <Field
              name = "afternoonTea"
              component = {SelectField}
              label = "Fruit for Afternoon Tea"
              options = {_.without(fruitOptions, morningTea)}
            />
        }}
    />
    

    我还在Sandbox 上为有相同问题的任何人创建了一个示例。

    【讨论】:

      【解决方案2】:

      如果您可以在“morningTea”字段中获取选项的值,则可以这样做假设该值存储为“morningTea.value”

      你可以像这样传入选项:

       <Field
         name = "afternoonTea"
         component = {SelectField}
         label = "Fruit for Afternoon Tea"
         options = {fruitOptions.filter(option => option != morningTea.value)}
       />
      

      我通过这个概念假设它:

       const q = [1,2,3,4,5]
          console.log(q) = "[1,2,3,4,5]"
      const y = q.filter(w => w != 1 )
          console.log(y) = "[2,3,4,5]"
      

      【讨论】:

      • 感谢您的回复 - 不幸的是,“morningTea”字段中的选项值是我无法访问的 - 它不像“morningTea.value”那么简单,所以看起来!我想我还是找到了答案……见下一条评论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      相关资源
      最近更新 更多