[英]How to type Stateless Functional Component using styled-component in React-Native with TypeScript?
Since one week we are using styled-component width React-Native and Typescript in my team project. 从一周开始,我们在团队项目中使用样式组件宽度React-Native和Typescript。
I'm forming myself on it and try to understand how to correctly use it with Typescript. 我正在形成自己,并尝试了解如何正确使用Typescript。
I actually have problem to understand how am I supposed to type a Stateless Functional Component with styled method. 我实际上有问题要理解我应该如何使用样式方法键入无状态功能组件。
Here is what I have following the doc : 以下是我遵循的文档 :
const SFCView: SFC<{}> = (props) => {
return <View style={props.style} />
}
const StyledSFCView = styled(SFCView)`
width: 100;
height: 100;
background-color: green
`;
Typescript says to me that props style does not exist in my type SFC<{}>
. 打字稿告诉我,我的类型
SFC<{}>
中不存在道具样式。 Indeed I defined it nowhere. 实际上我没有定义它。
I tried to tell typescript that my SFC
had those props 我试着告诉打字稿我的
SFC
有这些道具
const SFCView: SFC<{style: ViewStyle}> = (props) => {
return <View style={props.style} />
}
But when I use SFCView
somewhere else in my code typescript tell me that I have to specify all the props of a View. 但是当我在我的代码打字稿中的其他地方使用
SFCView
时告诉我,我必须指定View的所有道具。
Does anyone know how to correctly type it ? 有谁知道如何正确输入它?
After some research I found the standard for web with className . 经过一些研究,我找到了带有className的 web标准。
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
`;
Advantages: 好处:
style
prop in SFCView
. SFCView
没有关于style
道具的SFCView
。 style
prop is optional so I have no error when I use StyledSFCView
. style
prop是可选的,所以当我使用StyledSFCView
时没有错误。 Drawback: 退税:
style
is optional and developper can define it when they use StyledSFCView
. style
是可选的,开发人员可以在使用StyledSFCView
时定义它。 Now this is the last point I have to clarify. 现在,这是我必须澄清的最后一点。
You can write style(MyComponent)
, but for that to have an effect, you need to pass the prop className
, provided by styled-components
, to the final DOM element. 您可以编写
style(MyComponent)
,但为了产生效果,您需要将由styled-components
提供的prop className
传递给最终的DOM元素。
In your case, it should look something like this: 在你的情况下,它应该看起来像这样:
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>
)
Edit: As you mentioned, react-native
requires the prop style
instead of className
编辑:正如您所提到的,
react-native
需要prop style
而不是className
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.