0

我有一个 Button 和几个其他版本的按钮,它们希望重用 Button 但会覆盖一些特定规则。如宽度、高度、颜色或悬停状态颜色等。

这是否可能无需手动将每个属性作为道具传递?

这是 webpackbin 中的示例http://www.webpackbin.com/VyjrMGJ9f

import React from 'react';

import styled from 'styled-components';

const Button = styled.button`
  text-align: center;
  font: bold 15px helvetica;
  padding: 10px;
  border: 0;
  pointer-events: ${props => props.disabled ? 'none' : 'auto'};
  color: ${props => props.disabled ? '#848484' : '#fff'};
  background-color: ${props => props.disabled ? '#bebebe' : '#07314d'};
  &:hover {
    background-color: ${props => props.disabled ? '#bebebe' : '#336086'};
  }
`

const EnhancedButton = styled.button`
  background-color: ${props => props.disabled ? '#bebebe' : '#ec4800'};
  &:hover {
    background-color: ${props => props.disabled ? '#bebebe' : '#f98d00'};
  }
`

export default function HelloWorld() {
  return (
    <div>
      <p>
      <Button disabled>disabled button</Button> 
      and 
      <Button>button</Button>
      </p>
      <p>
      How can EnhancedButton in a different component re-use all of Button's rules and override some of them (in this case the background color and hovered background color? 
      <EnhancedButton disabled>disabled enhanced button</EnhancedButton>
      and 
      <EnhancedButton>enhanced button</EnhancedButton>
      </p>
    </div>
  );
}
4

1 回答 1

3

我刚刚想通了,很简单。

styled

可以将标签或组件作为参数,所以在这种情况下,我所要做的就是改变

const EnhancedButton = styled.button`

const EnhancedButton = styled(Button)`

这是 Webpackbin 上的工作版本http://www.webpackbin.com/VyjrMGJ9f

于 2017-03-01T02:27:00.723 回答