【问题标题】:How to type Stateless Functional Component using styled-component in React-Native with TypeScript?如何在带有 TypeScript 的 React-Native 中使用 styled-component 键入无状态功能组件?
【发布时间】:2019-09-16 22:45:35
【问题描述】:

自从一周以来,我们在我的团队项目中使用样式化组件宽度 React-Native 和 Typescript。

我正在努力理解如何正确使用 Typescript。

我的问题

我实际上很难理解我应该如何使用样式方法键入无状态功能组件。

实际代码

这是我关注doc的内容:

const SFCView: SFC<{}> = (props) => {
  return <View style={props.style} />
}

const StyledSFCView = styled(SFCView)`
  width: 100;
  height: 100;
  background-color: green
`;

我的错误

Typescript 告诉我,我的类型 SFC&lt;{}&gt; 中不存在道具样式。事实上,我没有在任何地方定义它。

我尝试了什么

我试图告诉 typescript 我的 SFC 有这些道具

const SFCView: SFC<{style: ViewStyle}> = (props) => {
  return <View style={props.style} />
}

但是当我在代码中的其他地方使用SFCView 时,打字稿告诉我必须指定视图的所有道具。

有人知道如何正确输入吗?

【问题讨论】:

  • 您希望 props.style 覆盖 StyledSFCView 的任何样式还是仅覆盖您当前拥有的样式,即宽度、高度和背景颜色?
  • @BenSmith 就是我的风格。

标签: typescript react-native styled-components


【解决方案1】:

你可以写style(MyComponent),但要让它生效,你需要将styled-components提供的prop className传递给最终的DOM元素。

在你的情况下,它应该是这样的:

const StyledView = styled(View)`
  width: 100;
  height: 100;
  background-color: green;
`;

const View = ({ className, ... otherPropsYouMightHave }) => (
  // Whatever you have in this component
  <div className={className}>
    // Whatever View needs to render
  </div>
)

编辑:正如你所提到的,react-native 需要 style 属性而不是 className

【讨论】:

  • 实际上对于 React-Native 我们需要使用style 而不是className(RN 组件不存在)。
  • 你说得对,react-native 需要style 而不是className 所以你自己的答案似乎是正确的,除了我认为SFCView 是多余的,你可以写@987654334 @ 直接让 View 处理可选的style prop styled-components.com/docs/basics#styling-any-components 看起来像
【解决方案2】:

经过一番研究,我找到了带有 className 的网络标准。

我目前更好的解决方案

import { SFC } from 'react';
import { StyleProp, ViewStyle } from 'react-native';

interface IProps {
 style?: StyleProp<ViewStyle>
}

const SFCView: SFC<IProps> = (props) => {
  return <View style={props.style} />
}

const StyledSFCView = styled(SFCView)`
  width: 100;
  height: 100;
  background-color: green
`;

优点:

  • SFCView 中的 style 属性不再出现错误。
  • style prop 是可选的,所以当我使用 StyledSFCView 时没有错误。

缺点:

  • style 是可选的,开发者可以在使用StyledSFCView 时定义它。

现在这是我必须澄清的最后一点。

【讨论】:

  • 如果您希望样式道具是强制性的,请删除问号
猜你喜欢
  • 2017-04-06
  • 2016-04-17
  • 2020-03-09
  • 1970-01-01
  • 2017-03-10
  • 2021-12-19
  • 2018-03-24
  • 2021-03-08
  • 2021-07-13
相关资源
最近更新 更多