jlt*_*lor 7 typescript reactjs
我在整个 Typescript 应用程序中使用 React Function 组件。
我正在尝试动态更新另一个组件中的一些子组件,如下所示:
const memoizedIterateAndAddProps = useCallback(
(kids: ReactNode) => {
return React.Children.map(kids, (child) => {
if (React.isValidElement(child)){
console.log(child.type.name)
}
}
}, [])
Run Code Online (Sandbox Code Playgroud)
但打字稿一直抱怨Property 'name' does not exist on type 'string | JSXElementConstructor<any>'. Property 'name' does not exist on type 'string'.ts(2339)
我知道这与孩子可能只是一个字符串这一事实有关,但我无法找到一种让 Typescript 满意的解决方法。
我将非常感谢任何人的帮助
...但我无法找到一种让 Typescript 满意的解决方法。
检查它是否不是字符串:
const memoizedIterateAndAddProps = useCallback(
(kids: ReactNode) => {
return React.Children.map(kids, (child) => {
if (React.isValidElement(child) && typeof child.type !== "string") {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
console.log(child.type.name);
}
});
}
);
Run Code Online (Sandbox Code Playgroud)
(或者&& "name" in child.type
也可以。)
type
当你<div/>
这样做时,你会得到一个字符串,所以如果你想使用name
.
归档时间: |
|
查看次数: |
4465 次 |
最近记录: |