[英]Error in declaring a variable inside the component class and outside the render function to use it inside the render function in react
[英]unable to use the variable declared outside the render function
为什么当我们在render函数外部声明一个对象并在组件的render函数的返回中使用它时会导致意外的令牌错误。 如果我在render函数中声明myStyle对象,则以下代码可以正常工作。
import React , { Component } from 'react';
class Test extends Component {
var myStyle={
backgroundColor:"red",
width:"100px",
height:"100px",
margin:"0 auto",
marginTop:"50px"
};
render(){
return(
<div style={myStyle}>
</div>
);
}
}
export default Test;
谢谢
首先,由于您使用的是ES6类语法,因此应使用const
或let
来定义变量。
不过,最好的解决方案是将变量设置为组件的状态。 因此,您以后可以轻松操作状态,并在需要时使用this.setState();
渲染组件this.setState();
。
您可以这样做:
在构造方法中,您可以执行以下操作-
constructor(props){
super(props);
this.state = {
myStyle: {
backgroundColor:"red",
width:"100px",
height:"100px",
margin:"0 auto",
marginTop:"50px"
}
}
}
之后,您可以使用ES6扩展运算符轻松地将CSS应用于所需的任何组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.