为什么子样式组件不应用样式?

时间:2020-09-07 16:08:03

标签: reactjs styled-components

我有一个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

结果是:

github-issue

问题在于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。
  • 该按钮不接受任何样式。

1 个答案:

答案 0 :(得分:0)

问题出在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)};
`;