我有一个班级,我想将道具传递给:
type TestProps = {
location: any
setMill: (value: any) => void
}
class TestClass extends Component<TestProps> {
componentDidMount() {
this.setState({ userRoleRating: 5 });
}
render() {
return <></>
}
}
export default withRouter(TestClass as any)
我有一个功能组件,我在其中调用类组件:
type LayoutProps = {
children?: React.ReactElement
setMill: (value: any) => void
}
const Layout: React.FC<LayoutProps> = (props: LayoutProps) => {
return <>
<TestClass />
<Container className="root-wrapper">{props.children}</Container>
<Footer />
</>
}
export default Layout
我试图像这样传递道具:
type LayoutProps = {
children?: React.ReactElement
setMill: (value: any) => void
}
const Layout: React.FC<LayoutProps> = (props: LayoutProps) => {
return <>
<TestClass setMill={props.setMill}/>
<Container className="root-wrapper">{props.children}</Container>
<Footer />
</>
}
export default Layout
但是我收到错误:
Type '{ setMill: (value: any) => void; }' is not assignable to type 'IntrinsicAttributes &
(IntrinsicClassAttributes<Component<Pick<RouteComponentProps<any,
StaticContext, unknown>, never> | (Pick<RouteComponentProps<any,
StaticContext, unknown>, never> & { ...; }), any, any>> &
Readonly<...>)'.
Property 'setMill' does not exist on type 'IntrinsicAttributes &
(IntrinsicClassAttributes<Component<Pick<RouteComponentProps<any,
StaticContext, unknown>, never> | (Pick<RouteComponentProps<any,
StaticContext, unknown>, never> & { ...; }), any, any>> &
Readonly<...>)'.ts(2322)
我认为原因可能是我导出类组件的方式(使用
withRouter
)。向其传递道具的正确方法是什么?
我想我找到了解决方案。我将
Layout
的属性传递给花括号中的 TestClass:
type LayoutProps = {
children?: React.ReactElement
setMill: (value: any) => void
}
const Layout: React.FC<LayoutProps> = (props: LayoutProps) => {
return <>
<TestClass {...props}/>
<Container className="root-wrapper">{props.children}</Container>
<Footer />
</>
}
export default Layout
它的工作原理正如预期的那样。如果我做错了什么请纠正我