【问题标题】:Property Y does not exist on type 'FunctionComponent<Interface>' even though Interface contains property Y属性 Y 不存在于类型“FunctionComponent<Interface>”上,即使接口包含属性 Y
【发布时间】: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


    【解决方案1】:

    在您展示的内容中,blockWrappers 是一个由React.ReactElement 组成的数组,每个数组都有一个孩子。那不是React.FunctionComponent&lt;BlockProps&gt;,是函数类型,是React.ReactElement&lt;BlockProps&gt;

    您可以通过React.Children.only 访问该单个孩子(如果有更多,您可以使用React.Children 上的其他方法之一):

    const child = React.Children.only<React.ReactElement<BlockProps>>(wrapper.props.children);
    

    然后就像使用包装器一样,您需要使用.props 来查看孩子的道具:

    console.log("blockClassName = ", child.props.blockClassName);
    

    例如:

    for (const wrapper of blockWrappers) {
        const child = React.Children.only<React.ReactElement<BlockProps>>(wrapper.props.children);
        if (child.props.blockClassName) {
            console.log("blockClassName = ", child.props.blockClassName);
        }
    }
    

    Playground link showing the types(我在您编辑之前创建的简化版本)

    【讨论】:

      猜你喜欢
      • 2020-11-24
      • 2021-09-19
      • 2018-03-29
      • 2016-11-14
      • 2021-12-15
      • 1970-01-01
      相关资源
      最近更新 更多