首先,我认为使用Set<MyEnum>
for useState
初始化好像不太好。
所以你可以写Options
像这样的组件:
function Options() {
const [greenVals, setGreenVals] = useState(new Set<MyEnum>());
const [redVals, setRedVals] = useState(new Set<MyEnum>());
const greenValue = { greenVals, setGreenVals };
const redValue = { redVals, setRedVals };
return (
<inputListContext.Provider
value={{
redValue,
greenValue,
}}
>
{/* whatever you want to pass */}
</inputListContext.Provider>
);
}
然后我们开始inputListContext
。您应该在您的外部声明一个接口Options
代表的组件inputListContext
类型,根据您在问题中提到的内容,它是这样的:
interface inputListContextType {
greenValue: { greenVals: Set<MyEnum>, setGreenVals: Dispatch<SetStateAction<Set<MyEnum>>> };
redValue: { redVals: Set<MyEnum>, setRedVals: Dispatch<SetStateAction<Set<MyEnum>>> };
}
接下来你创建inputListContext
不与null
类型和null
初始值。
const inputListContext = createContext<inputListContextType>({
greenValue: { greenVals: new Set<MyEnum>(), setGreenVals: () => { } },
redValue: { redVals: new Set<MyEnum>(), setRedVals: () => { } },
});