react-select 动态下拉列表,在用户输入时加载异步选项 [英] react-select dynamic dropdown with async options loaded as user is typing

查看:37
本文介绍了react-select 动态下拉列表,在用户输入时加载异步选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 的新手,我正在尝试合并 2 个不同的功能.一种动态表单,您可以在其中添加和/或删除输入和一个带有异步 react-select 的表单,您可以在其中开始输入一个单词,然后出现选项并根据 API 源(例如基于连接的用户)进行过滤

我快完成了(我想)但是:

当我开始输入时,我正确地看到了我的选项......并且选项被正确过滤但是当我点击一个项目(选择这个项目)时,我得到一个错误.

我得到的错误是 Cannot read property 'name' of undefined 但我不明白,我不确定这是我遇到的唯一问题.我不知道如何让我的选择正确地被选中并正确地放入我的对象数组 (inputFields)

这是我尝试混合的 2 个不同来源(它们都可以完美地独立放置)

React-Select 异步下拉列表:https://stackblitz.com/edit/react-select-async-component?file=index.js动态表单字段:https://www.youtube.com/watch?v=zgKH12s_95A

感谢您帮助我了解问题所在!!!

这是我的代码:

function AsyncDynamicForm(props) {const [inputFields, setInputFields] = useState([{ 名: '' },]);const [inputValue, setValue] = useState("");const handleChangeInput = (index, event) =>{const 值 = [...inputFields];值[索引][event.target.name] = event.target.value;setInputFields(values);};const AddFields = () =>{setInputFields([...inputFields, { firstName: '' }]);};const RemoveFields = (index) =>{const 值 = [...inputFields];values.splice(index, 1);setInputFields(values);};const loadOptions = (inputValue) =>{返回获取(`http://127.0.0.1:8000/api/Objects/?q=${inputValue}`).then((res) => res.json());};const handleInputChange = (value) =>{设置值(值)};const handleSubmit = (e) =>{e.preventDefault();console.log(inputFields", inputFields);//暂时没有};返回 (<div><容器><Form onSubmit={handleSubmit}>{inputFields.map((inputField, index) => (<div key={index}><Form.Field 内联><异步选择姓名=名字"值={inputField.firstName}onChange={(事件)=>handleChangeInput(索引,事件)}缓存选项默认选项getOptionLabel={(e) =>e.name.toString()}getOptionValue={(e) =>e.id}loadOptions={loadOptions}onInputChange={handleInputChange}/></Form.Field><Button.Group基本尺寸=小"><按钮图标=添加"onClick={() =>AddFields()}/><按钮图标=x";onClick={() =>RemoveFields(index)}/></Button.Group>

))}<按钮类型=提交"onClick={handleSubmit}>点击</按钮></表格></容器>

);}导出默认的 AsyncDynamicForm

解决方案

文档 很有帮助这里.onChange 道具采用具有特定签名的方法.

const onChange = (option, {action}) =>{/* `option` 值会有所不同,基于 Select 类型* 和动作,作为 `option` 之一,一个 `option` 数组*(在多选的情况下),`null`(清除时的典型* 一个选项),或 `undefined`.* 你实际得到的将取决于选择通过的`action`,* 是以下之一:* - '选择选项'* - '取消选择选项'* - '删除值'* - '流行值'* - '设定值'* - '清除'* - '创建选项'*///示例使用之前定义的 `useState` 钩子开关(动作){案例'选择选项',案例删除值",案例清除":设置颜色(选项);休息;默认://我现在不担心其他动作休息;}};

请记住,React-Select 将 value 视为整个 option 对象,而不仅仅是您在 getOptionValue<中定义的 option 值/代码>.如果您正在考虑设置一个真正的表单值",您可能会以某种方式包装 Select 来处理它.

React-Select 非常强大,也非常复杂.文档是您的朋友.我发现在尝试我还不完全理解的功能时,在 CodeSandbox 中玩玩会很有帮助.

I'm new to React and I'm trying to merge 2 different features. A dynamic form where you can add and/or remove inputs AND one with async react-select where you can start typing a word and options appear and get filtered based on an API source (based on connected user for example)

I'm almost done (I think) BUT :

When I start typing I correctly see my options...and options get filtered correctly BUT when I click on an item (to select this item) I get an error.

The error I got is Cannot read property 'name' of undefined but I don't understand it and I'm not sure it's the only problem I got. I have no clue how to get my choice to cprrectly get selected and correctly put into my array of objects (inputFields)

Here are the 2 different sources I try to mix (They both work perfectly put independantly)

React-Select Async dropdown : https://stackblitz.com/edit/react-select-async-component?file=index.js Dynamic form field : https://www.youtube.com/watch?v=zgKH12s_95A

Thank you for helping me understand what's the problem !!!

Here is my code :

function AsyncDynamicForm(props) {
  const [inputFields, setInputFields] = useState([
    { firstName: '' },
  ]);
  const [inputValue, setValue] = useState("");


  const handleChangeInput = (index, event) => {
    const values = [...inputFields];
    values[index][event.target.name] = event.target.value;
    setInputFields(values);
  };

  const AddFields = () => {
    setInputFields([...inputFields, { firstName: '' }]);
  };

  const RemoveFields = (index) => {
    const values = [...inputFields];
    values.splice(index, 1);
    setInputFields(values);
  };


  const loadOptions = (inputValue) => {
    return fetch(
      `http://127.0.0.1:8000/api/Objects/?q=${inputValue}`
    ).then((res) => res.json());
  };
    

  const handleInputChange = (value) => {
    setValue(value)
  };
  
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("inputFields", inputFields); // Nothing for now
  };


  return (
    <div>
        <Container>
          <Form onSubmit={handleSubmit}>
            {inputFields.map((inputField, index) => (
              <div key={index}>
                <Form.Field inline>
                  <AsyncSelect
                    name="firstName"
                    value={inputField.firstName}
                    onChange={(event) => handleChangeInput(index, event)}
                    cacheOptions
                    defaultOptions
                    getOptionLabel={(e) => e.name.toString()}
                    getOptionValue={(e) => e.id}
                    loadOptions={loadOptions}
                    onInputChange={handleInputChange}
                  />
                </Form.Field>
                <Button.Group basic size="small">
                  <Button icon="add" onClick={() => AddFields()} />
                  <Button
                    icon="x"
                    onClick={() => RemoveFields(index)}
                  />
                </Button.Group>
              </div>
            ))}
          
            <Button type="submit" onClick={handleSubmit}>
              click
            </Button>
          </Form>
        </Container>
    </div>
  );
}

export default AsyncDynamicForm

解决方案

The documentation is very helpful here. The onChange prop takes a method with a specific signature.

const onChange = (option, {action}) => {
  /* The `option` value will be different, based on the Select type
   * and the action, being one of `option`, an array of `option`s
   * (in the instance of a multiselect), `null` (typical when clearing
   * an option), or `undefined`.
   * What you actually get will depend on the `action` the select passes,
   * being one of:
   * - 'select-option'
   * - 'deselect-option'
   * - 'remove-value'
   * - 'pop-value'
   * - 'set-value'
   * - 'clear'
   * - 'create-option'
   */
   // example uses the `useState` hook defined earlier
   switch (action) {
     case 'select-option',
     case 'remove-value',
     case 'clear':
       setColor(option);
       break;
     default:
       // I'm not worried about other actions right now
       break;
   }
};

Remember that React-Select treats value as the entire option object, not just the option value you define in getOptionValue. If you're looking at setting a true form 'value', you'll probably wrap Select in some way to handle that.

React-Select is incredibly powerful, and incredibly complex. The documentation is your friend here. I find it helpful to play around in CodeSandbox, when trying out features I don't fully understand yet.

这篇关于react-select 动态下拉列表,在用户输入时加载异步选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆