如何在 TypeScript 中将值传递给 Context Provider?

2023-12-03

我正在尝试将我的反应脚本转换为打字稿,但在定义类型时遇到问题:

export const inputListContext = createContext<null>(null)

import {MyEnum} from "../ts-api-script";


type checkBoxParams = {
    myEnum: any
    name: any
}


export const Options = () => {

const [greenVals, setGreenVals] = useState(Set<MyEnum>);
const [redVals, setRedVals] = useState(Set<MyEnum>);

const greenValue = {greenVals, setGreenVals};
const redValue = {redVals, setRedVals};


return (
  <inputListContext.Provider value={{greenValue, redValue}}>
    <Checkbox myEnum={FirmStatusEnum.Op} name={"Option 1"}</Checkbox>
 </inputListContext.Provider>

)
}

我想做的就是将红色和绿色对象作为值传递给我的上下文提供程序。问题来自打字稿。

ERROR:
Type '{ greenValue: any; redValue: { redVals: { new (values?: readonly FirmStatusEnum[] | null | undefined): Set<MyEnum>; new (iterable?: Iterable<MyEnum> | null | undefined): Set<...>; readonly prototype: Set<...>; readonly [Symbol.species]: SetConstructor; }; setRedVals: React.Dispatch<...>; }; }' is not assignable to type 'null'

我需要采取哪些步骤来正确声明我的类型并纠正此问题?


首先,我认为使用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: () => { } },
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 TypeScript 中将值传递给 Context Provider? 的相关文章

随机推荐