使用 ReactJs 和 Typescript 在组件中调用主题 Props 时出错



我需要将主题的颜色传递给组件,我正在使用类型脚本(我是初学者(。

我遇到了一个我无法解决的错误。

错误是:参数 'props' 隐式具有 'any' 类型。ts(7006(

它出现在我的代码的颜色行中

<Linkxx
color={(props) => props.theme.colors.red}
size={11}
weight={500}
decoration={false}
/>

我的组件

import React from 'react';
import { Container } from './styles';
interface LinkProps {
color: string;
size?: number;
weight?: number;
decoration?: boolean;
}
const Link: React.FC<LinkProps> = ({ color, size, weight, decoration }) => {
return (
<Container
decoration={decoration}
weight={weight}
size={size}
color={color}
to="/teste"
>
teste
</Container>
);
};
export default Link;

出现问题的代码

import React from 'react';
import Header from '../../components/Header';
import Linkxx from '../../components/Link';
import {
Container,
Content,
UserCard,
Avatar,
UserData,
Canais,
BoxAction,
} from './styles';
const User: React.FC = () => {
return (
<>
<Header />
<Container>
<Content>
<h1>User</h1>
<UserCard>
<Avatar />
<UserData>
<span>Sample Name</span>
<small>sample@gmail.com</small>
</UserData>
<Canais>
<span>Adm, Manager</span>
<div>
<small>test</small>
<small>test</small>
<small>test</small>
</div>
</Canais>
<BoxAction>
<div>
<Linkxx
color={(props) => props.theme.colors.red}
size={11}
weight={500}
decoration={false}
/>
</div>
</BoxAction>
</UserCard>
</Content>
</Container>
</>
);
};
export default User;

调用组件时如何使用主题属性?

试试这个:

<Linkxx
// color={(props) => props.theme.colors.red} // You passed a function
color={props.theme.colors.red} // Try passing a value or string i.e. props.theme.colors.red
size={11}
weight={500}
decoration={false}
/>

正如您的界面所说color是字符串:

interface LinkProps {
color: string;  // color is string
size?: number;
weight?: number;
decoration?: boolean;
}

尝试将类型">any"添加到">props"参数中,如下所示:

color={(props: any) => props.theme.colors.red}
size={11}
weight={500}
decoration={false}

因为在打字稿中,您需要指定要发送的道具类型,或者采用定义的默认类型。 如果您不想指定任何类型,请明确要求组件期望状态和 props 为">any"类型。有关详细解决方案,请参阅本文:反应/打字稿:参数"props"隐式具有"any"类型错误

相关内容

最新更新