【问题标题】:Why child Styled-components is not applying styles?为什么子 Styled-components 不应用样式?
【发布时间】:2020-09-08 17:02:28
【问题描述】:

我有一个Notification 组件:


import React, { useContext } from "react"
import Wrapper from "./Wrapper"
import context from "./context"
import Close from "./Close"

const Notification = ({ children }) => {

    const { type } = useContext(context)

    return (<Wrapper type={type}>
        <Close /> {// This component does not apply styles !!}
        {children}
    </Wrapper>)
}

export default Notification

我的Wrapper:


import styled from "styled-components"

const Wrapper = styled.div`
      position:absolute;
      bottom:0;
      right:0;
      margin-right:1.2em;
      margin-bottom:1.2em;
      background-color: #fff;
      padding:15px;
      min-width:350px;
      min-height:100px;
      border-radius:20px;
      box-shadow: 0px 4px 30px 0px ${({ type }) => pickShadowColor(type)}}`

const pickShadowColor = (type) => {
    switch (type) {
        case "info": return "rgba(51,153,255,0.3)";
        case "warning": return "rgba(255,157,0,0.3)";
        case "success": return "rgba(0,216,0,0.3)";
        case "error": return "rgba(255,0,0,0.3)";
        default: return "rgba(190,190,190,0.3)";
    }
}

export default Wrapper

结果是:

问题在于Close 组件虽然具有自定义样式但仍显示默认样式button。

Close 组件:

import React from 'react';
import { Button } from './Button';

const Close = () => (
    <Button>close</Button>
)

export default Close;

以及样式化的Button:

import styled from 'styled-components';

export const Button = styled.button({
    'background-color': 'red'
})

预期行为

按钮应该是red。

实际行为

按钮具有默认样式。

附加信息

  • 导航器:Chrome。
  • 该按钮不接受任何样式。

【问题讨论】:

  • 这段代码对我有用,你能做一个可重现的例子吗? codesandbox.io/s/react-template-forked-19t49?file=/index.js
  • 你是在Chrome上运行的吗?
  • 你打开链接了吗?是的,我在 chrome 上检查了如何,为什么它相关?
  • 是的,我检查了链接,我想知道到底是什么问题,我会重现代码。

标签: reactjs styled-components


【解决方案1】:

问题在于box-shadow。您缺少一个 ; 并有一个额外的 {

从以下位置更改它:

box-shadow: 0px 4px 30px 0px ${({ type }) => pickShadowColor(type)}}`;

到:

box-shadow: 0px 4px 30px 0px ${({ type }) => pickShadowColor(type)};`;

完整的样式:

const Wrapper = styled.div`
  position: absolute;
  bottom: 0;
  right: 0;
  margin-right: 1.2em;
  margin-bottom: 1.2em;
  background-color: #fff;
  padding: 15px;
  min-width: 350px;
  min-height: 100px;
  border-radius: 20px;
  box-shadow: 0px 4px 30px 0px ${({ type }) => pickShadowColor(type)};
`;

【讨论】:

  • 没错,我今天解决了这个问题。投反对票的开发者应该向你道歉。
猜你喜欢
  • 2021-11-01
  • 2018-01-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2018-09-06
  • 2021-08-26
  • 2021-04-01
  • 2021-07-13
相关资源
最近更新 更多