【Typescript】报错:不能将xxx分配给“intrinsicAttribute“...

文章详细描述了在React应用中遇到的一个报错,该报错发生在父组件向子组件传递props时。通过三种方法解决了这个问题:明确子组件的类型定义、简化函数参数或直接在函数参数中指定props类型。这些解决方案可防止eslint警告并确保类型安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

intrinsicAttribute


报错复现

为了记录这个报错及处理,下面是代码复现:

src/App.tsx

import { useState } from "react";
import './app.less';
import Child from './Child';

const App: React.FC = () => {

    const [count, setCount] = useState(0);

    const handleClick = () => {
        setCount(count + 1);
    }

    return <>
        <h3>hello react!</h3>
        <button
            className="btn"
            onClick={handleClick}
        >You click it {count} times.</button>
        {/* 这里报错 */}
        <Child count={count} />
    </>
}

export default App;

src/Child.tsx

type ChildProp = {
    count?: number
}

const Child: React.FC = (props: ChildProp) => {

    const { count } = props;

    return <h3>{count}</h3>
}

export default Child;

报错:
在这里插入图片描述


解决

原因是子组件里没有做声明限制。修改子组件代码

方法一

type ChildProp = {
    count?: number
}

const Child: React.FC<ChildProp> = (props: ChildProp) => {

    const { count } = props;

    return <h3>{count}</h3>
}

export default Child;

方法二

type ChildProp = {
    count?: number
}

const Child: React.FC<ChildProp>= ({ count }) => {

    return <h3>{count}</h3>
}

export default Child;

方法三

type ChildProp = {
    count?: number
}

const Child: React.FC<ChildProp> = ({ count }: ChildProp) => {

    return <h3>{count}</h3>
}

export default Child;

如果后续有eslint报错,可以按照这个做xxx is missing…,可以一劳永逸的解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值