简体   繁体   English

无法使用在render函数外部声明的变量

[英]unable to use the variable declared outside the render function

why is that when we declare a object outside the render function and using it in the return of the render function of a component causes an unexpected token error . 为什么当我们在render函数外部声明一个对象并在组件的render函数的返回中使用它时会导致意外的令牌错误。 If i declare the myStyle object inside the render function the below code works correctly. 如果我在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;

Thanks 谢谢

First, since you're using ES6 class syntax, you should use const or let to define your variables. 首先,由于您使用的是ES6类语法,因此应使用constlet来定义变量。

The best solution for you though would be to set the variable into the state of the component. 不过,最好的解决方案是将变量设置为组件的状态。 So you can manipulate the state easily later and rerender the component when needed with this.setState(); 因此,您以后可以轻松操作状态,并在需要时使用this.setState();渲染组件this.setState(); .

You would do it like this: 您可以这样做:

Inside the constructor method you would do - 在构造方法中,您可以执行以下操作-

constructor(props){
    super(props);

    this.state = {
        myStyle: {
            backgroundColor:"red",
            width:"100px",
            height:"100px",
            margin:"0 auto",
            marginTop:"50px"
        }
    }
}

After that, you can use the ES6 spread operator to apply the CSS to whatever component you like, easily. 之后,您可以使用ES6扩展运算符轻松地将CSS应用于所需的任何组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM