按下图标时打开 react-select

Open react-select when you press on an icon

我正在尝试在您单击图标时打开 select 菜单。 我怎样才能做出反应?这是代码 我想删除默认的 select 我只想在您单击图标时打开 react-select

/* eslint-disable @typescript-eslint/no-unused-vars */
import Select, { components } from "react-select";

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useEffect, } from "react";

interface Props {
  avatarObj: any;
  // initalAvatarObj: any;
  avatarSvg?: any;
  // initialAvatarSvg?: any;
}

const CustomizeAvatar: React.FC<Props> = ({ avatarObj, avatarSvg }) => {

  const options = [
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' }
  ]

  return (
    <div className="relative flex items-center justify-center h-64 w-full">
      <div className="w-36" dangerouslySetInnerHTML={{ __html: avatarSvg }} />
      <FontAwesomeIcon icon='hat-cowboy' className="absolute top-1" />
      <div className="absolute top-7">
        <Select
          className="w-23"
          options={options}
        />
      </div>
    </div>
  )
};

export default CustomizeAvatar;


你需要一个状态来控制它。

const [open, setOpen] = useState(false)

<FontAwesomeIcon icon='hat-cowboy' className="absolute top-1" onClick={() => setOpen(!open)} />

{open && <Select
  className="w-23"
  options={options}
  menuIsOpen={open}
  placeholder=""
/>}

我自己设法解决了,你必须像这样更改默认样式 此处演示:https://gyazo.com/9fa746ce88c70272e264b0d040c40212

/* eslint-disable @typescript-eslint/no-unused-vars */
import Select from "react-select";

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {  useRef, useState } from "react";

interface Props {
  avatarObj: any;
  // initalAvatarObj: any;
  avatarSvg?: any;
  // initialAvatarSvg?: any;
}

const CustomizeAvatar: React.FC<Props> = ({ avatarObj, avatarSvg }) => {
  const selectRef = useRef<any>({});
  const [openMenu, setOpenMenu] = useState(false);
  const [open, setOpen] = useState(false)

  const options = [
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' }
  ]

  const customStyles = {
    option: (provided: any, state: { isSelected: any }) => ({
      ...provided,
      borderBottom: '1px dotted pink',
      color: state.isSelected ? 'red' : 'blue',
      width: 200,
    }),
    container: () => ({
      width: 200,
    }),
    control: () => ({
      border: "none",
      display: "none",
      width: 0,
    }),
  };


  return (
    <div className="relative flex items-center justify-center h-64 w-full" onClick={() => setOpen(!open)} >
      <FontAwesomeIcon icon='hat-cowboy' className="absolute top-1" onClick={() => setOpen(!open)} />
      <div className="absolute top-7">
        <Select
          placeholder=""
          styles={customStyles}
          options={options}
          menuIsOpen={open}
        />
      </div>
    </div>
  )
};

export default CustomizeAvatar;