【问题标题】:React-Emotion: pass down defaultProps to in component reuseReact-Emotion:将 defaultProps 传递给组件重用
【发布时间】:2018-10-17 13:23:49
【问题描述】:

我有这个:

import styled from 'react-emotion';

const Box = styled('div')`
  display: flex;
  flex-direction: ${p => p.direction};
`;

Box.defaultProps = {
  direction: 'column'
};

当我使用 Box 组件时,这很好用。默认道具如预期的那样存在。

但是,当我重用带有样式的 Box 时,默认道具不会被传递:

import styled from 'react-emotion';
import Box from './Box';

export const UniqResponsiveBox = styled(Box)`
  // some media queries and other new styles
`;

当我使用 UniqResponsiveBox 时,它没有我为 Box 声明的 defaultProps。以下解决方法让我通过,但似乎多余,我相信我错过了仅使用情感来完成此任务的东西。

import styled from 'react-emotion';

const BoxContainer = styled('div')`
  display: flex;
  flex-direction: ${p => p.direction};
`;

function Box(props) {
  return <BoxContainer {...props}/>
}

Box.defaultProps = {
  direction: 'column'
}

import styled from 'react-emotion';
import Box from './Box';

export const UniqResponsiveBox = styled(Box)`
  // some responsive queries and other uniq styles
`;

// In this scenario, the default props are there because I passed them explicitly. Helppp!

【问题讨论】:

    标签: javascript css reactjs styled-components emotion


    【解决方案1】:

    这个特殊问题是 Emotion 中的一个错误 - 它已在 11 天前合并的 a pull request 中修复,因此它应该会出现在下一个版本中。

    与此同时,避免附加功能的另一种解决方法是:

    import styled from 'react-emotion';
    import Box from './Box';
    
    export const UniqResponsiveBox = styled(Box)`
      // some media queries and other new styles
    `;
    
    UniqResponsiveBox.defaultProps = Box.defaultProps
    

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 2022-11-19
      • 1970-01-01
      • 2017-11-17
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 2019-12-17
      相关资源
      最近更新 更多