【问题标题】:Add styles to Styled Component custom Component in React Native在 React Native 中为 Styled Component 自定义组件添加样式
【发布时间】:2018-12-14 00:00:12
【问题描述】:

我有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 中的扩展样式?

【问题讨论】:

    标签: javascript reactjs react-native styled-components


    【解决方案1】:

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

    • 扩展按钮样式:

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

    • 将道具传递给按钮:
    const Button = styled.button'
    
    /* ...your props */
    
    margin: ${props => props.withMargin ? '10px' : '0px'};
    

    然后调用 render 方法你可以调用它:

    <Button withMargin  {...restProps} /> 
    

    【讨论】:

    • with & extend API 被标记为已折旧。还有其他方法吗?我不想将 props 传递给每个样式属性进行自定义...
    猜你喜欢
    • 2021-03-07
    • 2020-06-09
    • 2019-06-14
    • 2021-09-25
    • 1970-01-01
    • 2020-07-07
    • 2022-11-29
    • 1970-01-01
    • 2021-10-31
    相关资源
    最近更新 更多