在React Native中为Styled Component自定义组件添加样式

5
我有一个名为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中扩展样式的含义?

1个回答

0

有两种方法可以使它工作:

  • 扩展按钮样式:

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

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

/* ...your props */

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

然后在render方法中调用,你可以使用以下方式调用:

<Button withMargin  {...restProps} /> 

withextend API已被标记为过时。还有其他方法可以实现吗?我不想为自定义每个样式属性传递props... - Kaydarin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接