如何在反应组件中使用样式组件

Isa*_*aac 4 javascript css reactjs styled-components

使用时完全是新手styled-components。我想知道它有什么用?样式化后应该如何实现组件生命周期方法?为了简单起见,我删除了所有其他样式。

import styled from 'styled-components';

const Button = styled.button`
  background-color: 'green'
`

export default Button;

Run Code Online (Sandbox Code Playgroud)

我想知道如何进一步研究这个Button组件?

传统上我们可以声明一个基于类的组件并实现一些生命周期方法,但现在有了 this styled-components,我不太确定如何将它们组合在一起,因为它们实际上是单个Button组件?

更新:

的完整源代码Button.js。通过使用下面的代码,所有样式都会消失,我无法理解问题

import React from 'react';
import styled from 'styled-components';
// import Button from 'react-bootstrap/Button';

import color from '../config/color';

const Button = ({ children, onPress }) => (
  <button type="button" onPress={onPress}>{children}</button>
);

const StyledButton = styled(Button)`
  width: 12rem;
  height: 54px;
  font-size: 1rem;
  background-color: ${(props) => {
    if (props.inverted) return 'white';
    if (props.disabled) return color.disabled;
    return (props.color || color.primary);
  }};
  color: ${(props) => {
    if (props.disabled) return color.disabledText;
    if (props.inverted) return (props.color || color.primary);
    return 'white';
  }};
  border:${(props) => (props.inverted ? `2px solid ${props.color || color.primary}` : 'none')};
  border-radius: 60px;

  &:hover {
    filter: ${(props) => (props.inverted || props.disabled ? 'none' : 'brightness(95%)')}
  }
`;

export default StyledButton;

Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 5

为了设置自定义反应组件的样式,您可以将自定义组件名称作为参数传递给styled. 根据文档:

styled 方法可以在您自己的所有组件或任何第三方组件上完美运行,只要它们将传递的 className 属性附加到 DOM 元素即可。

import React from 'react';
import styled from 'styled-components';
// import Button from 'react-bootstrap/Button';

import color from '../config/color';

const Button = ({ children, className onPress }) => (
  <button type="button" className={className} onPress={onPress}>{children}</button>
);

const StyledButton = styled(Button)`
  width: 12rem;
  height: 54px;
  font-size: 1rem;
  background-color: ${(props) => {
    if (props.inverted) return 'white';
    if (props.disabled) return color.disabled;
    return (props.color || color.primary);
  }};
  color: ${(props) => {
    if (props.disabled) return color.disabledText;
    if (props.inverted) return (props.color || color.primary);
    return 'white';
  }};
  border:${(props) => (props.inverted ? `2px solid ${props.color || color.primary}` : 'none')};
  border-radius: 60px;

  &:hover {
    filter: ${(props) => (props.inverted || props.disabled ? 'none' : 'brightness(95%)')}
  }
`;

export default StyledButton;
Run Code Online (Sandbox Code Playgroud)

阅读styled-component documentation有关样式化任何组件的更多详细信息