React样式组件不传递道具

时间:2020-07-30 13:29:40

标签: javascript reactjs styled-components react-functional-component

我所做的:
我正在将一些道具传递给功能组件 Stat.jsx

我所期望的:
我需要将一些背景渐变颜色代码作为string类型的属性传递给 Stat.jsx 组件,以创建自定义颜色元素。

发生了什么事
道具不会传递给 Stat.jsx ,而且道具对象为空。

Stat.jsx

import React from 'react';
import styled from 'styled-components';

const Stat = styled.div`
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 2.5em;
    width: auto;
    height: 2.5em;
    border-radius: 0.5em;
    box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
    background: linear-gradient(160deg, ${(props) => console.log(props) });
    font-size: 1.8em;
    font-family: Rubik-Medium;
    color: #fff;
`;

// console.log(props) is returning object: { children: "1000", theme: {} }

export default ({ value }) => <Stat>{value}</Stat>;



Stats.jsx

import React from 'react';
import Stat from './Stat';
import styled from 'styled-components';

const Stats = styled.div`
    display: flex;
`;

export default () => (
    <div>
        <Stats>
            <Stat value="1000" background="#F4D03F, #16A085" />
        </Stats>
    </div>
);

2 个答案:

答案 0 :(得分:2)

快速修复

因为您没有将背景道具传递给实际的Stat组件:

import React from 'react';
import styled from 'styled-components';

const StyledStat = styled.div`
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 2.5em;
    width: auto;
    height: 2.5em;
    border-radius: 0.5em;
    box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
    background: linear-gradient(160deg, ${(props) => console.log(props) });
    font-size: 1.8em;
    font-family: Rubik-Medium;
    color: #fff;
`;


export default function Stat(props){
    const { value } = props;
    
    return (
       <StyledStat {...props}>
          {value}
       </StyledStat>;

};

说明

一种更好的方式来说明此问题是通过重命名组件:

{{1}}

答案 1 :(得分:0)

样式化的组件道具通常来自ThemeProvider,这就是为什么您在theme内进行console.logging时看到styled.div道具的原因。

通常在App.js中,您会有类似的内容:

// src/App.jsx

import React from 'react'
import { ThemeProvider } from 'styled-components';

const theme: {
   colors: {
     primary: blue,
   }
}

const App = () => (
  <ThemeProvider theme={theme}>
    <Stat />
  </ThemeProvider>
)

export default App;

您可以使用以下命令访问这些属性 ${(props) => props.theme.colors.primary } 因为样式组件为每个StyledComponents提供了theme道具(后面有上下文提供者/消费者的东西)

import React from 'react';
import styled from 'styled-components';

const Stat = styled.div`
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 2.5em;
    width: auto;
    height: 2.5em;
    border-radius: 0.5em;
    box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
    background: linear-gradient(160deg, ${(props) => props.theme.colors.primary} });
    font-size: 1.8em;
    font-family: Rubik-Medium;
    color: #fff;
`;