简体   繁体   中英

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 . If i declare the myStyle object inside the render function the below code works correctly.

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.

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(); .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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