【发布时间】:2021-11-03 16:06:47
【问题描述】:
我有 3 个组件,Grid、BlockWrapper 和 Block。
Block 是 BlockWrapper 的子代。
Block 具有我在界面中指定的 props blockClassName 和 text:
网格/index.tsx
const blockWrappers:Array<JSX.Element> = [];
const blocks:Array<JSX.Element> = [];
// ...
for(let i = 0; i < 16; i++) {
blocks.push(
<Block
blockClassName={ blockClassName }
text={i + ""}
/>
);
blockWrappers.push(
<BlockWrapper index={i} >
{ blocks[i] }
</BlockWrapper>
)
}
// ...
interface BlockProps {
blockClassName: string,
text: string
}
swappable.on("swappable:swapped", () => {
for(let wrapper of blockWrappers) { // blockWrappers is an array of BlockWrapper
let child = wrapper.props.children as React.FunctionComponent<BlockProps>; // Getting child of BlockWrapper, which is Block
if(child.blockClassName) console.log(); // Error: Property 'blockClassName' does not exist on type 'FunctionComponent<BlockProps>'.ts(2339)
}
updateClasses();
});
块/index.tsx
const Block = ( {blockClassName, text}: {blockClassName: string, text: string} ) => {
if(blockClassName.includes("isEmpty")) text = "";
return (
<span className={blockClassName}>
<Content>
<h1>{text}</h1>
</Content>
</span>
);
}
但是,当我尝试从作为 FunctionComponent 的 child 访问 blockClassName 时,它给了我一个错误,说属性“blockClassName”在 child 中不存在。我已经在 BlockProps 中指定它有一个名为“blockClassName”的属性,但我不明白为什么会出现错误。我该如何解决这个问题?
提前致谢。
【问题讨论】:
标签: reactjs typescript react-typescript