如何将React默认样式与样式道具结合起来?

问题描述 投票:0回答:1

我有以下ui组件:

...
import stylePropType from 'react-style-proptype';

const Heading = ({
  ...
  marginBottom,
  strong
}) => (
  <Header
    style={{
      marginBottom,
      fontWeight: strong ? 'bold' : 'normal',
    }}
  >....
  </Header>
);

Heading.defaultProps = {
  children: <div />,
  marginBottom: 4,
  strong: false,
  style: {},
};

Heading.propTypes = {
  children: PropTypes.node,
  marginBottom: PropTypes.number,
  strong: PropTypes.bool,
  style: stylePropType,
};

如何将当前样式逻辑(marginBottom和fontWeight)与作为prop传入的可选其他样式组合在一起?有没有办法将两者合并或合并?

javascript reactjs
1个回答
5
投票

您可以在传入的样式中使用扩展语法(...):

  <Header
    style={{
      marginBottom,
      fontWeight: strong ? 'bold' : 'normal',
      ...this.props.style
    }}
  >....
  </Header>
© www.soinside.com 2019 - 2024. All rights reserved.