reactjs:如何在react-select中通过特定值设置默认值?

dwbf0jvd  于 2023-04-29  发布在  React
关注(0)|答案(3)|浏览(153)

首先,让我说,我搜索了很多关于这个问题,但我不能解决我的问题。
默认情况下,我有一个特定的值,我希望在视图中的选择框中显示该值。
选择代码:

<Select
      options={getMainCategory.data.map((item) => {
        return { value: item.id, label: item.categoryName };
      })}
       defaultValue={getMainCategory.data.find((x)=>{
        const c = x.id === mainparentId;
        return { value: c.id, label: c.categoryName };
       })}
      onChange={onOptionChange}
/>

我用上面的代码做了,但没有工作。如果你能指导我,我将不胜感激。

whlutmcx

whlutmcx1#

代码中的问题是你正在使用defaultValue函数,它必须是stringnumberobject。在示例中,您必须使用value属性,如下所示:

<Select
  options={getMainCategory.data.map((item) => {
    return { value: item.id, label: item.categoryName };
  })}
  defaultValue={getMainCategory.data.find((x) => x.id === mainparentId).value}
  onChange={onOptionChange}
/>
kzmpq1sx

kzmpq1sx2#

import { useState, useEffect } from 'react';
import Select from 'react-select';

function MyComponent() {
  const [options, setOptions] = useState([]);
  const [defaultValue, setDefaultValue] = useState(null);

  useEffect(() => {
    // Make API call to fetch options from database
    fetch('/api/options')
      .then(response => response.json())
      .then(data => {
        // Set options state
        setOptions(data);

        // Find default option in data and set defaultValue state
        const defaultOption = data.find(option => option.value === 'option2');
        setDefaultValue(defaultOption);
      });
  }, []);

  return (
    <Select
      options={options}
      defaultValue={defaultValue}
    />
  );
}
myss37ts

myss37ts3#

你可以这样使用它

import React, { useState } from 'react';
import Select from 'react-select';

const options = [
  { value: 'apple', label: 'Apple' },
  { value: 'banana', label: 'Banana' },
  { value: 'orange', label: 'Orange' },
];

const MySelect = () => {
  const [selectedOption, setSelectedOption] = useState(null);

  // set the default value to 'Banana'
  const defaultValue = options.find((option) => option.value === 'banana');

  return (
    <Select
      options={options}
      value={selectedOption}
      onChange={setSelectedOption}
      defaultValue={defaultValue}
    />
  );
};

在本例中,defaultValue属性被设置为与值“banana”匹配的选项对象。第一次渲染组件时,默认情况下将选择“香蕉”选项。
您可以将默认值更改为任何其他选项,方法是查找其对应的选项对象并将其作为defaultValue传递。

相关问题