我正在尝试让我的组件使用样式组件在react-native中使用动态样式。这样做的方法在这里显示https://github.com/styled-components/styled-components/issues/940
const ColorAnimation = styled.div.attrs({
style: props => ({
color: props.color
})
})`
// static styles
它也适用于React Native,如下所示。 https://snack.expo.io/ryIXsAe0M
import React, { Component } from 'react';
import { View } from 'react-native';
import styled from 'styled-components/native'; // 2.2.4
const StyledView = styled.View.attrs({
style: props => ({
backgroundColor: props.backgroundColor,
height: props.height,
}),
})`
background-color: papayawhip;
`;
const StyledText = styled.Text`
color: palevioletred;
`;
const RotatedBox = styled.View`
transform: rotate(90deg);
text-shadow-offset: 10px 5px;
font-variant: small-caps;
margin: 5px 7px 2px;
`;
export default class App extends Component {
render() {
return (
<View style={{ marginTop: 50 }}>
<StyledView height={100} backgroundColor="yellow">
<StyledText>Hello World!</StyledText>
</StyledView>
<RotatedBox />
</View>
);
}
}
但是,我宁愿只传入一个包含我想要使用的所有动态样式的customStyle prop。像这样。 。 。 https://snack.expo.io/BkpToRe0f
const StyledView = styled.View.attrs({
style: props => props.customStyles,
})`
background-color: papayawhip;
`;
<StyledView customStyles={{ height: 100, backgroundColor: 'yelllow' }}>
不幸的是,这不适用于样式。有人知道为什么吗?如果有替代解决方案?
对于想要更详细解释何时在样式组件中使用additional props
的人,我将快速举例说明attrs
的工作原理。也称为附加额外道具。你可以在styled components documentation上看到它。
下面是使用CSS的背景图像的简单示例。我需要为可访问性目的应用标题和aria-label。这样做的一种方法是附加额外的道具。
// Component
getBackgroundImage = () => {
const { imageUrl, altTag } = this.props;
return (
<BackgroundImage
imageUrl={imageUrl}
altTag={altTag}
/>
);
};
// Styled component
export default styled.div.attrs({
title: props => props.altTag,
'aria-label': props => props.altTag,
role: 'img,
})`
background: url(${props => props.imageUrl}) center center/ cover no-repeat;
height: 400px;
width: 100%;
`;
然后,我将能够在DOM中找到此组件,我将能够看到这些属性。我相信这是对此的正确用法,并将您对其他道具和静态样式的关注区分开来。
关于这个问题:
不幸的是,这不适用于样式。有人知道为什么吗?
我认为它不起作用,因为backgroundColor
不是一个属性。高度是一个适用于certain HTML elements的属性,可以通过此链接找到。
其他HTML属性可以找到here
因此,为了让您的Style Component显示正确的样式,不需要qazxsw poi。
attrs
有关const StyledView = styled.View`
background-color: ${props => props.backgroundColor};
height: ${props => props.height};
`;
<StyledView height={100} backgroundColor="yelllow" />
和attaching-additional-props的更多信息。它们都包含非常有用的信息和示例。
我觉得你对如何使用样式组件感到有点困惑
这是你给出的例子:
attrs API
这应该是这样的:
const StyledView = styled.View.attrs({
style: props => ({
backgroundColor: props.backgroundColor,
height: props.height,
}),
})`
background-color: papayawhip;
`;
虽然第一个就像你说的那样工作,但第二个更干净,你可以使用组件而不必传递额外的customStyles道具。样式组件为您服务
const StyledView = styled.View`
height: ${props => props.height},
background-color: ${props => props.backgroundColor ? "papayawhip"};
`;