如何在React中使用样式化组件?

时间:2018-08-07 11:40:56

标签: reactjs styled-components

请原谅我的困惑和新鲜感。我正在尝试导出样式化的Button。完全茫然和困惑。请帮忙。我并不是真的想导出2个按钮,如图所示,但是我想导出一个按钮,其中包含道具的样式,并将给定样式作为默认样式,我想:(

import React, {Component} from 'react'
import ReactDOM from 'react-dom'

import styled, { css } from 'styled-components'


export default class Button extends React.Component {
  btn: Btn = (props) => {
      styled.button`
      border-radius: 3px;
      padding: 0.25em 1em;
      margin: 0 1em;
      background: transparent;
      color: palevioletred;
      border: 2px solid palevioletred;

      ${props => props.primary && css`
        background: palevioletred;
        color: white;
      `}
    `
  }

  render(
    <Btn>Normal Button</Btn>
    <Btn primary>Primary Button</Btn>
  )
}

还有与我相关的App元素

import React, { Component } from 'react'
import 'containers/App.css'
import Button from 'components/Button'

export default class App extends Component {
    render() {
      return (
        <div>
          <p>
            <Button primary="primary" label="Button Help" />
          </p>
        </div>
      )
    }
  }

1 个答案:

答案 0 :(得分:0)

如下定义您的样式按钮

import React from 'react';
import styled, {css} from 'react-emotion';

const StyledButton = styled('button')`
  border-radius: 3px;
  padding: 0.25em 1em;
  margin: 0 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;
`;
const primary = css`
  background: black;
  color: white;
`;
export default class Button extends React.Component {
  render() {
    return (
      <div>
        <StyledButton className={this.props.primary && `${primary}`}>
          {this.props.label}
        </StyledButton>
      </div>
    );
  }
}

在应用程序元素中,按如下方式使用按钮

import React, { Component } from 'react'
import 'containers/App.css'
import Button from 'components/Button'

export default class App extends Component {
    render() {
      return (
        <div>
          <p>
            <Button label="Button Help" /> // for normal Styled Button
            <Button primary label="Button Primary" /> // for Primary Styled Button                
          </p>
        </div>
      )
    }
  }