Bil*_*ill 2 typescript reactjs
我试图将一个函数传递给一个子组件,但我收到了一些打字稿错误......
父.tsx
import React from 'react';
import {Child} from './child';
const Parent: React.FC = () => {
function fire() {
console.log('fire')
}
return (
<Child fire={fire}/>
// ^___ error here!
)
}
Run Code Online (Sandbox Code Playgroud)
错误fire是Type '{ fire: () => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
Property 'fire' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.ts(2322)
孩子.tsx
import React from 'react';
const Child: React.FC = (props: any) => {
return (
<p onClick={props.fire}>Click Me</p>
)
}
export {Child};
Run Code Online (Sandbox Code Playgroud)
您在错误的位置添加了类型。如果您将鼠标悬停在上面,React.FC您会看到它接受一个参数并且默认值为{},这意味着没有默认情况下不可用的道具(如props.children)。添加该参数。
在参数中分配类型 as(props: any)不提供该类型信息。当您在中定义该参数时,您可以将其省略React.FC
import React from 'react';
interface ChildProps {
fire: () => void
}
const Child: React.FC<ChildProps> = (props) => {
return (
<p onClick={props.fire}>Click Me</p>
)
}
export {Child};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3144 次 |
| 最近记录: |