代码之家  ›  专栏  ›  技术社区  ›  Thuan Nguyen

如何在formik中将select字段添加到FieldArray中

  •  0
  • Thuan Nguyen  · 技术社区  · 7 年前

    我遵循以下准则:

    import React from 'react';
    import { Formik, Form, Field, FieldArray } from 'formik';
    
    // Here is an example of a form with an editable list.
    // Next to each input are buttons for insert and remove.
    // If the list is empty, there is a button to add an item.
    export const FriendList = () => (
      <div>
        <h1>Friend List</h1>
        <Formik
          initialValues={{ friends: ['jared', 'ian', 'brent'] }}
          onSubmit={values =>
            setTimeout(() => {
              alert(JSON.stringify(values, null, 2));
            }, 500)
          }
          render={({ values }) => (
            <Form>
              <FieldArray
                name="friends"
                render={arrayHelpers => (
                  <div>
                    {values.friends && values.friends.length > 0 ? (
                      values.friends.map((friend, index) => (
                        <div key={index}>
                          <Field name={`friends.${index}`} />
                          <button
                            type="button"
                            onClick={() => arrayHelpers.remove(index)} // remove a friend from the list
                          >
                            -
                          </button>
                          <button
                            type="button"
                            onClick={() => arrayHelpers.insert(index, '')} // insert an empty string at a position
                          >
                            +
                          </button>
                        </div>
                      ))
                    ) : (
                      <button type="button" onClick={() => arrayHelpers.push('')}>
                        {/* show this when user has removed all friends from the list */}
                        Add a friend
                      </button>
                    )}
                    <div>
                      <button type="submit">Submit</button>
                    </div>
                  </div>
                )}
              />
            </Form>
          )}
        />
      </div>
    );
    

    但对于文本输入字段。 我想换成 select 我也会这样做。

    替换:

    <Field name={`issues.${index}`} />
    

    致:

    <Field component="select" name="color">
      <option value="red">Red</option>
      <option value="green">Green</option>
      <option value="blue">Blue</option>
    </Field>
    

    我添加3个组件当我在一个组件中选择值时,它对所有组件都有效。

    我这里怎么了?

    1 回复  |  直到 7 年前
        1
  •  4
  •   onyx    7 年前

    这个 name 每个的属性 select 输入必须是唯一的。尝试以下操作

    <Field component="select" name={`friends.${index}`}>
       <option value="red">Red</option>
       <option value="green">Green</option>
       <option value="blue">Blue</option>
    </Field>