React 样式组件中的 'this' 关键字有问题吗?
Trouble with 'this' keyword in React 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
样式组件写得像函数组件,这意味着没有 this。你能做的是${(props) => props.xLeftPercent}
.
我目前正在尝试使用样式化组件,但我很难像往常一样创建组件。更具体地说,我在 '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
样式组件写得像函数组件,这意味着没有 this。你能做的是${(props) => props.xLeftPercent}
.