React Select组件封装
import React, { useContext, useEffect, useRef, useState } from 'react'
//判断受控与非受控组件的钩子
import { useAutoControlledState } from './useAutoControlledState'
//使用context可以支持各种嵌套
const SelectContext = React.createContext()
function Option({ value, children, ...rest }) {
const context = useContext(SelectContext)
if (context === undefined)
throw new Error('Select.Option must be used within Select')
const { state, setState, finalOptions, setFinalOptions } = context
//useEffect是异步的
useEffect(() => {
setFinalOptions((prev) =>
//先筛选掉再进行拼接 避免重复
prev.filter((item) => item.value !== value).concat({ value, children })
)
//由于依赖发生改变的话也会触发useEffect 所以要在他每次return的时候筛选一遍 return 是每一次都会触发的
return () =>
setFinalOptions((prev) => prev.filter((item) => item.value !== value))
}, [value, children, se