如何为样式组件声明“ propTypes”?

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

我正在开发一个反应库,例如MyLib,所以我想为我的lib用户提供propTypes。但是,将打字稿和样式化组件结合使用,会导致以下错误:

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

根据以下代码库,我应该为Scroller声明什么类型?(当前我只能使用any类型来解决编译错误)

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,
}
reactjs typescript styled-components react-proptypes
1个回答
0
投票

我会做这样的事情

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: object) => <ScrollerStyle {...props} />;

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

注意:我几乎不了解TS,所以我不确定'props:'部分是否正确,但是您得到了历史记录。

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