[英]How to define custom props in a react functional component with typescript?
I just started a new react project with typescript and I'm having difficulty defining a custom prop in a functional component.我刚刚用 typescript 开始了一个新的 React 项目,但我在功能组件中定义自定义道具时遇到了困难。
I looked up how to define custom props and I found a way of defining an interface detailing the type of prop I'm passing in to the function, but when I try to run it on my main App, I get an error saying我查看了如何定义自定义道具,并找到了一种定义接口的方法,该接口详细说明了我传递给 function 的道具类型,但是当我尝试在我的主应用程序上运行它时,我收到一条错误消息
Type '{ digit: number;
输入'{数字:数字; }' is not assignable to type 'IntrinsicAttributes'.
}' 不可分配给类型 'IntrinsicAttributes'。 Property 'digit' does not exist on type 'IntrinsicAttributes'.
“IntrinsicAttributes”类型上不存在属性“digit”。 TS2322
TS2322
My code:我的代码:
import React from 'react';
import Button from '@mui/material/Button';
export {}
interface NumberButton {
digit:number,
}
function NumberButton(props:NumberButton){
return (
<Button variant="contained" color="primary">{props.digit}</Button>
)
}
import React from 'react';
import ReactDOM from 'react-dom';
import ClearButton from './Components';
import NumberButton from './Components';
export default function App(){
return (
<div>
<ClearButton/>
<NumberButton digit={1}/>
</div>
)
}
I'm trying to get more familiar with functional components after using hooks and I'm hooked on using them.在使用 hooks 之后,我试图更加熟悉功能组件,并且我迷上了使用它们。
export {}
Currently you're not exporting the NumberButton component, so that's the main thing that needs fixing.目前您没有导出 NumberButton 组件,因此这是需要修复的主要问题。 Additionally, you're using the same variable name for both the component and the props.
此外,您为组件和道具使用了相同的变量名。 Try this:
尝试这个:
import React from 'react';
import Button from '@mui/material/Button';
interface NumberButtonProps {
digit: number,
}
function NumberButton(props: NumberButtonProps){
return (
<Button variant="contained" color="primary">{props.digit}</Button>
)
}
export default NumberButton;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.