如何将 props 传递给扩展 Component 的类<Props>?

问题描述 投票:0回答:1

我有一个班级,我想将道具传递给:

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
)。向其传递道具的正确方法是什么?

reactjs typescript class react-props
1个回答
0
投票

我想我找到了解决方案。我将

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

它的工作原理正如预期的那样。如果我做错了什么请纠正我

© www.soinside.com 2019 - 2024. All rights reserved.