简体   繁体   English

React TS 共享样式组件道具

[英]React TS shared styled component props

What is the right way to let typescript know about props in shared component:让打字稿知道共享组件中的道具的正确方法是什么:

import styled from 'styled-components'
import React, { forwardRef } from 'react'

export const Input = forwardRef<HTMLInputElement, React.ComponentPropsWithoutRef<'input'>>(({ err, ...rest }, ref) => {
  return <StyledInput {...rest} ref={ref} />
})

const StyledInput = styled.input`
  box-shadow: inset 0 0 0 1px ${({ err, theme }) => (err ? theme.badColor : theme.primaryColor)};
`

First issue:首要问题:

Property 'err' does not exist on type 'Pick, HTMLInputElement>, "form" |属性 'err' 在类型 'Pick, HTMLInputElement>, "form" 上不存在 | "style" | "风格" | "title" | “标题” | "pattern" | “模式” | "key" | “钥匙” | "accept" | “接受” | "alt" | "替代" | "autoComplete" | “自动完成” | ... 276 more ... | ... 276 更多... | "onTransitionEndCapture"> & { ...; "onTransitionEndCapture"> & { ...; } & ThemeProps<...>' } & ThemeProps<...>'

Second issue: theme is of type any, but have an interface in provider:第二个问题:主题是任何类型,但在提供者中有一个接口: 在此处输入图片说明

Third issue:第三题: 在此处输入图片说明

You can create an type for your styled-components props:你可以为你的样式组件道具创建一个类型:

type StyledInputProps = {
  err?: string
}

const StyledInput = styled.input<StyledInputProps>`
  // your styles...
`;

For your theme you have to create your own theme type.对于您的主题,您必须创建自己的主题类型。 Example:例子:

type ThemeType = {
  colors: {
    primary: string,
  }
};

const theme: ThemeType = {
  colors: {
    primary: '#F47829',
  }
};

const App = () => (
  <ThemeProvider theme={theme}>
    // ...
  </ThemeProvider>
);

Documentation: https://www.styled-components.com/docs/api#typescript .文档: https : //www.styled-components.com/docs/api#typescript

To pass your error into your 'Input'-component you have to create one more type for that one (alternatively you can use the same type if all props are the same):要将您的错误传递到您的“输入”组件中,您必须为该组件创建另一种类型(或者,如果所有道具都相同,您可以使用相同的类型):

type InputProps = {
  err?: string
};

const Input: React.FC<InputProps> = forwardRef(({ ...rest }, ref) => {
    return <StyledInput {...rest} ref={ref} />
});

Or using the type as the second type parameter for forwardRef :或者使用类型作为forwardRef的第二个类型参数:

const Input = React.forwardRef<HTMLInputElement, InputProps>(({ ...rest }, ref) 
  => <StyledInput {...rest} ref={ref} />);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM