[英]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.