Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
Why isnt this React variable working in my state object?
class Squares extends React.Component {
    constructor() {
        super();
        this.color = 'blue';
    }

    state = {
        backgroundColor: this.color,
        width: "50px",
        height: "50px"
    };


    render () {

        return (
            <div>
                <div style={this.state}>Hello</div>
                <button>Add Square</button>
                <p>{this.state.backgroundColor}</p>
            </div>
        );
    }


}

this.color is outputting its value, but I cant assign it to this.state.backgroundColor. I eventually want to add a onClick event to the button and when I click it, i want to output a square with the color changed.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The primary issue here is actually just how JS works - any variables defined outside the constructor are initialized before the constructor. For example:

class Squares {
    constructor() {
        this.color = 'blue';
    }

    state = {
        backgroundColor: this.color,
        otherBackgroundColor: 'blue'
    };


    render () {
        console.log(this.state.backgroundColor)
        console.log(this.state.otherBackgroundColor)
    }
}

const s = new Squares();
s.render();

So if you need to access this.color, and you initialize it in the constructor, you need to initialize this.state in your constructor as well.

class Squares {
    constructor() {
        this.color = 'blue';
        this.state = {
            backgroundColor: this.color,
        }
    }

  
    render () {
        console.log(this.state.backgroundColor)
    }
}

const s = new Squares();
s.render();

about 4 years ago · Juan Pablo Isaza Relatório

0

this.color = 'blue'; is not state managed.

constructor() {
    super();
    this.state = {
        backgroundColor: 'blue',
        width: "50px",
        height: "50px"
    };
  }

this should work and instead of changing color update the value of backgroundColor

about 4 years ago · Juan Pablo Isaza Relatório

0

Some working code with button to add square and select to change background color of square.

Working codesandbox link - https://codesandbox.io/s/nice-chaplygin-0m87u

import React, { Component } from "react";

class Squares extends Component {
  state = {
    showSquare: false
  };

  handleClick = () => {
    this.setState({
      showSquare: true
    });
  };

  handleChange = ({ target }) => {
    this.setState({
      backgroundColor: target.value
    });
  };

  render() {
    const { backgroundColor, showSquare } = this.state;
    return (
      <div>
        <div style={{ backgroundColor }} className={showSquare && "square"}>
          Hello
        </div>
        <button onClick={this.handleClick}>Add Square</button>
        <select onChange={this.handleChange}>
          <option value="red">red</option>
          <option value="purple">purple</option>
          <option value="green">green</option>
        </select>
      </div>
    );
  }
}

export default Squares;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda