带有 Chakra UI 的 TypeScript 支持 StyleProps 的正确方法是什么?

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

在父组件上收到错误消息:

输入 '{ bar: string; py:字符串; }' 不可分配给类型“IntrinsicAttributes & Props”。 类型“IntrinsicAttributes & Props”上不存在属性“py”。ts(2322)

父组件:

// striped code
export default async function parent() {
  const data = await apiLogic() 

  return (
    <Flex>
      <Child bar={data?.bar} py="6" />
    </Flex>
  )
}

子组件:

interface Props {
  bar: string
  props: any
}

export default function Child({ bar, ...props }: Props) {
  return (
    <Box {...props}>
      // code stripped
    </Box>
  )
}

研究:

用 TypeScript 传播

props
时,我应该在这里实施,有什么特殊的方法吗?如何解决 Chakra UI StyledProps
py
的错误?

typescript react-props chakra-ui intrinsicattributes
1个回答
0
投票

Chakra UI 导出每个组件的道具类型,因此您可以使用 Chakra UI 的道具来扩展您自己的自定义界面,包括

py
。由于该组件在将自定义 props 传播到 Box 之前会对其进行解构,因此这应该可以修复 Typescript 警告。

Box
的示例:

import { Box, type BoxProps, Flex, Text } from '@chakra-ui/react'

// Extend the exported prop interface for the Chakra UI component
interface CustomProps extends BoxProps {
  bar: string;
}

// Use the custom interface that extends Box props and destructure out your custom prop additions
export const Child = ({ bar, ...chakraProps }: CustomProps) => {
  // Pass the rest of the Chakra component props to Box
  return (
    <Box {...chakraProps}>
      <Text>{bar}</Text>
    </Box>
  )
}

export const Parent = () => {
  const data = { bar: 'foo' }

  return (
    <Flex>
      <Child bar={data.bar} py="6" />
    </Flex>
  )
}

export const App = () => {
  return <Parent />
}

CodeSandbox 链接

注:Chakra UI 2.8.2 版本时编写

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