【发布时间】:2021-10-23 00:31:18
【问题描述】:
我正在使用 React Children 和 React Clone 元素,目标是在 Option 组件的 onClick 事件中触发包装器和 Select 组件中的方法。一切正常。但是我在调用 Option 组件时遇到类型错误。
代码:
import React, {
useState,
Dispatch,
SetStateAction,
Children,
cloneElement,
ReactElement,
ReactNode
} from "react";
type OptionProps = {
setSelectedInSelect: Dispatch<SetStateAction<string>>;
setSelectedInWrapper: Dispatch<SetStateAction<string>>;
fruit: string;
};
function Option({
setSelectedInSelect,
setSelectedInWrapper,
fruit
}: OptionProps) {
return (
<li
onClick={() => {
setSelectedInSelect(fruit);
setSelectedInWrapper(fruit);
}}
>
{fruit}
</li>
);
}
type SelectProps = {
children: ReactNode;
};
function Select({ children }: SelectProps) {
const [selectedInSelect, setSelectedInSelect] = useState<string>("");
return (
<div>
<div>
<div>selected in select: {selectedInSelect}</div>
</div>
<ul>
{Children.map(children, (child) => {
return cloneElement(child as ReactElement, {
setSelectedInSelect
});
})}
</ul>
</div>
);
}
function Wrapper() {
const [selectedInWrapper, setSelectedInWrapper] = useState<string>("");
const fruits = ["Apple", "Orange"];
return (
<div style={{ margin: "20px" }}>
<div style={{ marginBottom: "15px" }}>
<div>selected in wrapper: {selectedInWrapper}</div>
</div>
<Select>
{fruits.map((fruit) => {
return (
<Option // ERROR HERE
key={fruit}
fruit={fruit}
setSelectedInWrapper={setSelectedInWrapper}
/>
);
})}
</Select>
</div>
);
}
export default Wrapper;
错误是:
Property 'setSelectedInSelect' is missing in type '{ key: string; fruit: string; setSelectedInWrapper: Dispatch<SetStateAction<string>>; }' but required in type 'OptionProps'.
当我克隆组件时,setSelectedInSelect 被传递给 Option。我怎样才能摆脱类型问题?
代码沙盒:https://codesandbox.io/s/infallible-swartz-fjnkm?file=/src/Select.tsx
【问题讨论】:
-
有没有机会将此代码移动到沙箱以重现错误?
-
@DennisVash 在帖子末尾添加了代码框链接。
标签: reactjs typescript