reactjs - styled-component için "propTypes" nasıl tanımlanır?


Bir React kütüphanesi, diyelim ki MyLib, geliştiriyorum, bu yüzden kütüphane kullanıcılarım için propTypes sağlamak istiyorum. Ancak, TypeScript ve styled-components kombinasyonu ile bu, aşağıdaki hataya yol açıyor:

Property 'propTypes' does not exist on type 'StyledComponent<"div", any, ScrollerProp, never>'.ts(2339)

Aşağıdaki kod tabanına göre, Scroller için hangi türü beyan etmeliyim? (Şu anda derleme hatasını çözmek için sadece any türünü kullanabiliyorum)

MyLib.d.ts

export type ScrollerProp = {
  maxHeight: number,
}

MyLib.tsx

import PropTypes from 'prop-types'
import styled from 'styled-components'

const Scroller: any = styled.div<ScrollerProp>`
  overflow-x: auto;
  overflow-y: visible;
  max-width: 100%;
  float: left;
  width: auto;
  ${({ maxHeight }) => maxHeight && css`
    max-height: ${maxHeight}px;
  `}
`

Scroller.propTypes = {
  maxHeight: PropTypes.number,
}

Cevap #1

Benim de benzer, hatta aynı problemim vardı. Benim için işe yarayan şuydu:

import styled from 'styled-components'

const Scroller: any = styled.div<{maxHeight: number}>`
  overflow-x: auto;
  overflow-y: visible;
  max-width: 100%;
  float: left;
  width: auto;
  ${({ maxHeight }) => maxHeight && css`
    max-height: ${maxHeight}px;
  `}
`

Türümü harici olarak tanımlamak işe yaramadı, ancak doğrudan koymak işe yaradı. Styled Components Belgelerine göre - Özel özellikleri kullanma

Cevap #2

Böyle bir şey yapardım

import PropTypes from 'prop-types'
import styled from 'styled-components'

const ScrollerStyle: any = styled.div<ScrollerProp>`
  overflow-x: auto;
  overflow-y: visible;
  max-width: 100%;
  float: left;
  width: auto;
  ${({ maxHeight }) => maxHeight && css`
    max-height: ${maxHeight}px;
  `}
`;

const Scroller = (props: any) => <ScrollerStyle {...props} />;

Scroller.propTypes = {
  maxHeight: PropTypes.number,
};

Not: TS'i zar zor biliyorum, bu yüzden 'props: ' kısmının doğru olup olmadığından emin değilim, ama ne demek istediğimi anlarsınız.