Typescript - 当为React组件进行类型定义时,IntrinsicAttributes和children类型问题

7

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

Footer.tsx

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

export default Footer;

ParentComponent.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: any; }”。类型“{ children: Element; }”不能赋值给类型“{ children: any; inModal: any; }”。属性“inModal”在类型“{ children: Element; }”中不存在。

我不太确定这是什么意思。如果能提供帮助,将不胜感激。


如果您在 Footer 组件中给 inModal 设置默认值为 false,您是否仍然会收到错误? const Footer = ({ children, inModal = false }) ... - Tholle
不,当我给一个默认值时,错误就消失了。您能否解释一下为什么会这样,并且我可以接受您的答案吗? - noblerare
我认为CRice在下面给出了非常好的答案。 - Tholle
2个回答

13
错误表明 Footer 组件需要传递一个名为 inModal 的 props。要解决这个问题,你可以选择以下两种方法之一:
1. 给它一个默认值。 2. 在使用 Footer 组件时,将 inModal 属性传递给它。
const Footer = ({ children, inModal = false }) => ...

告诉TypeScript它是可选的:

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

或者每当您使用页脚时明确提供该属性:

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

3
抱歉挖掘一个旧问题,但你能解释一下这个错误是怎么引起的吗?什么是"IntrinsicAttributes"?在类型系统中发生了什么,导致默认值的缺失会导致该错误?(我也遇到了同样的错误,但这些解决方案对我没有用。我正在寻求更深入的理解。)抱歉挖掘一个旧问题,您能解释一下这个错误的含义吗?"IntrinsicAttributes"是什么?类型系统中缺少默认值所导致的错误是怎么回事?(我也遇到了同样的错误,但这些解决方案对我没有用。我正在寻求更深入的理解。) - JakeRobb
4
在这种情况下,整个推断只来自错误的最后一部分:“类型'{children:Element}'中缺少属性'inModal'”,这表明它非常直接。由于标记了该 prop 为必填项,类型系统显示了一个错误;它不能像最初编写的那样未指定(有关详细信息,请参见答案)。至于“IntrinsicAttributes”?它是表示所有 React 组件都必须接受的 props 的类型(请注意:只有一个可选的 string | number prop,即 key)。如果您真的卡住了,也许考虑提一个新问题? - CRice

0

我看了你的代码,发现你没有指定inModal props的类型。我认为定义接口是一个很好的做法,像这样:

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

你可以像这样修改:

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

export class ParentComponent extends React.Component<FooterPropsType> {


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接