【问题标题】:How to access props in the component using react and typescript?如何使用 react 和 typescript 访问组件中的道具?
【发布时间】:2020-05-22 11:46:35
【问题描述】:

我想使用 react 和 typescript 访问 react 功能组件中的 props。

我有 MainComponent,它有 Layout 组件,我将 prop isOpen 从 MainComponent 传递给 Layout 组件,如下面的代码所示,

const Layout: React.FC = ({children}) => ( //how to access isOpen prop here
    <>
        <leftNav />
            {children}
        <RightNav isOpen={isOpen} />
    </>
);
interface Props {
    item: item;
}
function Main({ item }: Props) {
    return (
        <Wrapper>
            <Switch>
                <Route
                    path="/items"
                    render={routeProps => (
                        <Layout isOpen={isOpen}> //passing prop here
                            <Items />
                        </Layout>
                   )}
                />
            </Switch>
        </Wrapper>
    )
}

我已经尝试像下面这样访问它

interface Props {
    children: any;
    isOpen: boolean;
}
const Layout: React.FC = ({children, isOpen}: Props) => (
    <>
        <leftNav />
            {children}
        <RightNav isOpen={isOpen} />
    </>
);

但是上面抛出错误jsxelement is not assignable to type FC组件。

谁能帮我解决这个问题。谢谢。

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    React.FC 是通用的,并为 props 接受类型参数。你可以这样写你的布局组件。

    interface Props {
        isOpen: boolean; 
        // if you want isOpen props to be optional
        // isOpen?: boolean;
    }
    
    const Layout: React.FC<Props> = ({children, isOpen}) => (
        <>
            <leftNav />
                {children}
            <RightNav isOpen={isOpen} />
        </>
    );
    
    

    您的主要组件很好。

    【讨论】:

      【解决方案2】:

      您需要输入FC 泛型的道具:

      //interface Props { ... }
      
      const Layout: React.FC<Props> = ({children, isOpen}) => (
          <>
              <leftNav />
                  {children}
              <RightNav isOpen={isOpen} />
          </>
      );
      

      完全省略FC

      //interface Props { ... }
      
      const Layout: ({children, isOpen}: Props) => (
          <>
              <leftNav />
                  {children}
              <RightNav isOpen={isOpen} />
          </>
      );
      

      【讨论】:

        猜你喜欢
        • 2021-01-26
        • 2020-05-04
        • 1970-01-01
        • 2019-07-27
        • 2021-06-25
        • 2020-12-07
        • 2021-01-13
        • 1970-01-01
        • 2020-08-20
        相关资源
        最近更新 更多