繁体   English   中英

Typescript - 键入 React 组件时 IntrinsicAttributes 和子类型问题

[英]Typescript - IntrinsicAttributes and children type issues when typing React components

我正在将我的 React 文件迁移到.tsx并遇到了这个问题。

页脚.tsx

const Footer = ({ children, inModal }) => (
    <footer className={'(inModal ? " in-modal" : "") }>
        <div>
            {children}
        </div>
    </footer>
);

export default Footer;

父组件.tsx

import Footer from 'path/to/Footer';

export class ParentComponent extends React.Component<{ showSomething: (() => void) }> {
    render() {
        return (
            <Footer>
                <Button onClick={() => this.props.showSomething()}>Add</Button>
            </Footer>
        );
    }
}

<Footer>标签下方有红色下划线,错误如下:

[ts] 输入'{ children: Element; }' 不可分配给类型 'IntrinsicAttributes & { children: any; inModal:任何; }'。 输入'{ children: Element; }' 不可分配给类型 '{ children: any; inModal:任何; }'。 类型 '{ children: Element; 中缺少属性 'inModal' }'。

我不太确定如何破译这意味着什么。 任何帮助将不胜感激。

该错误表明Footer组件需要将prop inModal传递给它。 要解决此问题,您可以:

给它一个默认值:

const Footer = ({ children, inModal = false }) => ...

告诉打字稿它是可选的:

const Footer = ({ children, inModal }: {children: any, inModal?: boolean}) => ...

或者在使用页脚时明确提供prop:

<Footer inModal={false}> ... </Footer>

我看到你的代码,发现你没有指定 inModal 道具的类型,我相信这样定义接口是一个很好的做法:

export class ParentComponent extends React.Component<{ showSomething: (() => void) }> {

你可以像这样修改它:

interface FooterPropsType{
showSomething?:()=> void,
isModal?: boolean,
}

export class ParentComponent extends React.Component<FooterPropsType> {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM