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 está generando su valor, pero no puedo asignarlo a this.state.backgroundColor. Eventualmente quiero agregar un evento onClick al botón y cuando hago clic en él, quiero generar un cuadrado con el color cambiado.
El problema principal aquí es en realidad cómo funciona JS: cualquier variable definida fuera del constructor se inicializa antes que el constructor. Por ejemplo:
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(); Entonces, si necesita acceder a this.color y lo inicializa en el constructor, también debe inicializar this.state en su constructor.
class Squares { constructor() { this.color = 'blue'; this.state = { backgroundColor: this.color, } } render () { console.log(this.state.backgroundColor) } } const s = new Squares(); s.render();this.color = 'blue'; no es administrada por el estado.
constructor() { super(); this.state = { backgroundColor: 'blue', width: "50px", height: "50px" }; }esto debería funcionar y, en lugar de cambiar el color, actualice el valor de backgroundColor
Algún código de trabajo con botón para agregar cuadrado y seleccionar para cambiar el color de fondo del cuadrado.
Enlace de trabajo de codesandbox: 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;