在react-final-form组件

时间:2018-02-07 02:16:19

标签: react-final-form final-form

我在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”列表不是它自己的字段。

2 个答案:

答案 0 :(得分:4)

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

基本上,文档遗漏了FormRenderProps类型还有一个&#39;值&#39;支柱。从这里开始,在react-final-form装饰的组件中,您可以访问props.values,并将值从那里传递给其他组件/字段。

E.g。

<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为所有有相同问题的人创建了一个例子。

答案 1 :(得分:0)

如果您可以在“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]"