【问题标题】:How to use styled-components in React?如何在 React 中使用样式化组件?
【发布时间】:2019-01-14 11:51:47
【问题描述】:

请原谅我的困惑和新手。我正在尝试导出样式按钮。完全头晕目眩。请帮忙。我真的不想导出 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>
      )
    }
  }

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    如下定义样式按钮

    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>
        );
      }
    }
    

    在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 label="Button Help" /> // for normal Styled Button
                <Button primary label="Button Primary" /> // for Primary Styled Button                
              </p>
            </div>
          )
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 2020-09-26
      • 1970-01-01
      • 2021-09-06
      • 2021-04-13
      • 2021-03-08
      • 1970-01-01
      • 2017-07-11
      • 2019-10-18
      相关资源
      最近更新 更多