在 React Native 中为 Styled Component 自定义组件添加样式
Add styles to Styled Component custom Component in React Native
我有 button.js
:
import React from "react";
import styled from "styled-components";
const StyledButton = styled.TouchableOpacity`
border: 1px solid #fff;
border-radius: 10px;
padding-horizontal: 10px;
padding-vertical: 5px;
`;
const StyledButtonText = styled.Text`
color: #fff;
font-size: 12;
`;
export default ({ children }) => (
<StyledButton>
<StyledButtonText>{children.toUpperCase()}</StyledButtonText>
</StyledButton>
);
及其用法:
import React, { Component } from "react";
import styled from "styled-components";
import Button from "./button";
const StyledNavView = styled.View`
justify-content: flex-end;
flex-direction: row;
background: #000;
padding-horizontal: 10px;
padding-vertical: 10px;
`;
const StyledTodayButton = styled(Button)`
margin: 10px;
`;
export default class Nav extends Component {
render() {
return (
<StyledNavView>
<StyledTodayButton>Today</StyledTodayButton>
<Button>Previous</Button>
</StyledNavView>
);
}
}
问题是,我在 StyledTodayButton
中应用的保证金实际上从未应用过。我是否误解了在 Styled Components 中扩展样式?
有两种方法可以让它发挥作用:
- 扩展按钮样式:
const StyledTodayButton = Button.extend'margin: 10px'
- 将道具传递给按钮:
const Button = styled.button'
/* ...your props */
margin: ${props => props.withMargin ? '10px' : '0px'};
然后在 render 方法中调用你可以调用它:
<Button withMargin {...restProps} />
我有 button.js
:
import React from "react";
import styled from "styled-components";
const StyledButton = styled.TouchableOpacity`
border: 1px solid #fff;
border-radius: 10px;
padding-horizontal: 10px;
padding-vertical: 5px;
`;
const StyledButtonText = styled.Text`
color: #fff;
font-size: 12;
`;
export default ({ children }) => (
<StyledButton>
<StyledButtonText>{children.toUpperCase()}</StyledButtonText>
</StyledButton>
);
及其用法:
import React, { Component } from "react";
import styled from "styled-components";
import Button from "./button";
const StyledNavView = styled.View`
justify-content: flex-end;
flex-direction: row;
background: #000;
padding-horizontal: 10px;
padding-vertical: 10px;
`;
const StyledTodayButton = styled(Button)`
margin: 10px;
`;
export default class Nav extends Component {
render() {
return (
<StyledNavView>
<StyledTodayButton>Today</StyledTodayButton>
<Button>Previous</Button>
</StyledNavView>
);
}
}
问题是,我在 StyledTodayButton
中应用的保证金实际上从未应用过。我是否误解了在 Styled Components 中扩展样式?
有两种方法可以让它发挥作用:
- 扩展按钮样式:
const StyledTodayButton = Button.extend'margin: 10px'
- 将道具传递给按钮:
const Button = styled.button'
/* ...your props */
margin: ${props => props.withMargin ? '10px' : '0px'};
然后在 render 方法中调用你可以调用它:
<Button withMargin {...restProps} />