代码之家  ›  专栏  ›  技术社区  ›  noblerare

使用react功能组件作为类型

  •  4
  • noblerare  · 技术社区  · 7 年前

    我能够使用react类组件(即 React.Component )作为类型,但无法使用功能性/无状态组件。下面是一个例子:

    import Footer from 'path/to/component/Footer';
    
    interface ComponentProps {
        customFooter: (Footer)
    }
    
    class MyComponent extends React.Component<ComponentProps> {
        render() {
            return (
                <div>
                    {this.props.customFooter}
                </div>
            );
        }
    }
    

    页脚.tsx

    const Footer: React.StatelessComponent<{ children?: any }> = ({ children }) => (
        <footer>
            <div>
                {children}
            </div>
        </footer>
    );
    
    export default Footer;
    

    红色下划线在 (Footer) 内容如下: Cannot find name 'Footer' 是的。

    我发现如果我使用react类组件而不是函数组件,我的问题就会消失。为什么我不能使用一个功能组件,我有办法这样做吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   jmattheis zzz    7 年前

    页脚不是一种类型,它只是一个变量,用于获取可以使用的类型 typeof

    const Footer: React.StatelessComponent<{ children?: any }> = ({ children }) => (
        <footer>
            <div>
                {children}
            </div>
        </footer>
    );
    
    interface ComponentProps {
        customFooter: typeof Footer    
    }
    

    然后你可以这样使用它:

    class MyComponent extends React.Component<ComponentProps> {
        render() {
            const {customFooter: CustomFooter} = this.props;
            return (
                <div>
                    {<CustomFooter>footer children</CustomFooter>}
                </div>
            );
        }
    }
    
    const MainComponent = () => {
        return (<MyComponent customFooter={Footer}/>)
    };
    

    如果要将实际的jsx元素添加为如下值:

    const MainComponent = () => {
        return (<MyComponent customFooter={<Footer>footer children</Footer>}/>)
    };
    

    然后您需要将customfooter的类型设置为react.reactnode:

    interface ComponentProps {
        customFooter: React.ReactNode
    }