javascript - react 情绪 : pass down defaultProps to in component reuse

标签 javascript css reactjs styled-components emotion

我有这个:

import styled from 'react-emotion';

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

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

当我使用 Box 组件时,它工作得很好。默认 Prop 如预期的那样存在。

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

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!

最佳答案

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

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

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

关于javascript - react 情绪 : pass down defaultProps to in component reuse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50219259/

相关文章:

javascript - 如何使用 javascript/jquery - session/cookies/etc 获取用户信息

javascript - 获取 Bootstrap 弹出元素的 ID

javascript - 在 Google Apps Script 中的函数内调用函数(invoke)

html - 将标题向左移动,似乎无法弄清楚? (HTML/CSS)

javascript - 将图像 URL 转换为 dataURL - Javascript

reactjs - 与 getDerivedStateFromProps 中之前的 prop 进行比较

javascript - 当变量通过 URL 传递时,PHP 页面加载空白

html - 除非使用开发人员工具,否则网站无法正确缩放

javascript - jQuery Page 在单页中按下按键时每次向下滚动

javascript - React 内联条件组件属性