在React样式的组件中遇到'this'关键字的问题?

时间:2018-06-04 14:42:13

标签: javascript reactjs styled-components

我目前正在尝试使用样式化组件,但我很难像平常一样创建组件。更具体地说,我收到了'this'关键字的错误,并传递了属性。

在我的主JavaScript文件中,我尝试创建一个这样的组件(对我来说很正常):

let newStyledComponent = <HomePageDiv property1 = {property1} ... />

在HomePageDiv.js中,我有一个常量是div,一个常量是这个div将设置的关键帧:

import React from 'react';

import styled, { keyframes } from 'styled-components';

export const HomePageDiv = styled.div`
    height: 100vh;
    width: 100vw;
    display: flex;
    flex-direction: column;
    position: absolute;
    overflow: hidden;
    animation: ${backgroundChange} 4s ease-in-out 0s infinite;
`

const backgroundChange = keyframes`
    0%, 100% {
        background: radial-gradient(ellipse at ${this.props.xLeftPercent+`%`} ${this.props.yLeftPercent+'%'}, rgba(${this.leftR + this.leftRStep * 0}, ${this.leftG + this.leftGStep * 0}, ${this.leftB + this.leftBStep * 0}, 0.5), transparent),
                    radial-gradient(ellipse at ${this.props.xRightPercent+`%`} ${this.props.yRightPercent+'%'}, rgba(${this.rightR + this.rightRStep * 0}, ${this.rightG + this.rightGStep * 0}, ${this.rightB + this.rightBStep * 0}, 0.5), transparent);
    }

    ...

    99% {
        ...
    }
`

export default HomePageDiv;

鉴于此,为什么我会收到错误:

Uncaught TypeError: Cannot read property 'props' of undefined

同样,如果我拿走'this'关键字,我也会得到:

Uncaught ReferenceError: props is not defined

1 个答案:

答案 0 :(得分:5)

样式化的组件被写成功能组件,这意味着没有这个。你可以做的是${(props) => props.xLeftPercent}