在React Native中向样式化组件自定义组件添加样式

时间:2018-07-05 13:19:08

标签: javascript reactjs react-native styled-components

我有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中应用的边距实际上从未应用过。我是否误解了样式化组件中的样式扩展?

1 个答案:

答案 0 :(得分:0)

有两种方法可以使其起作用:

  • 扩展按钮样式:

const StyledTodayButton = Button.extend'margin: 10px'

  • 将属性传递给按钮:
const Button = styled.button'

/* ...your props */

margin: ${props => props.withMargin ? '10px' : '0px'};

然后调用render方法,您可以使用以下方法调用它:

<Button withMargin  {...restProps} />