【问题标题】:How to type compound components with ref forwarding如何使用 ref 转发键入复合组件
【发布时间】:2020-07-09 16:53:15
【问题描述】:

我正在尝试自定义 Chakra-ui 选项卡组件。根据他们的文档,它必须包裹在React.forwardRef 中,因为他们使用cloneElement 在内部传递状态。但随后 TS 抱怨:

[tsserver 2559] [E] Type '{ children: string; }' has no properties in common with type 'IntrinsicAttributes & { isSelected?: boolean | undefined; } & RefAttributes<HTMLElement>'.

是否可以将类型添加到CoolTab 组件,以便它仍然可以与他们的 api 一起使用?

const CoolTab = React.forwardRef<HTMLElement, { isSelected?: boolean }>((props, ref) => {
  return (
    <Tab ref={ref} isSelected={props.isSelected} {...props}>
      {props.isSelected ? '????' : '????'}
      {props.children}
    </Tab>
  )
})

CoolTab.displayName = 'CoolTab'

const Module = () => {
  return (
    <CenterLayout>
      <Card>
        <Tabs>
          <TabList>
            <CoolTab>General</CoolTab>
            <Tab>Notifications</Tab>
          </TabList>

          <TabPanels>
            <TabPanel>
              <p>one!</p>
            </TabPanel>
            <TabPanel>
              <p>two!</p>
            </TabPanel>
          </TabPanels>
        </Tabs>
      </Card>
    </CenterLayout>
  )
}

https://chakra-ui.com/tabs#creating-custom-tab-components

【问题讨论】:

    标签: javascript reactjs typescript chakra


    【解决方案1】:

    我最终这样输入了我的组件:

    const BottomSheet: React.ForwardRefExoticComponent<BottomSheetProps> & {Header?: React.FC }
    
    BottomSheet.Header = ({ children }) => { return <h1>Header</h1> }
    

    这仍然有使 Header 属性可选的缺点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-14
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 2022-01-27
      相关资源
      最近更新 更多