簡體   English   中英

為什么這個 React 變量在我的狀態對象中不起作用?

[英]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 正在輸出它的值,但我不能將它分配給 this.state.backgroundColor。 我最終想向按鈕添加一個 onClick 事件,當我點擊它時,我想輸出一個顏色改變的方塊。

這里的主要問題實際上就是 JS 是如何工作的——在構造函數之外定義的任何變量都在構造函數之前被初始化。 例如:

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

因此,如果您需要訪問this.color ,並在構造函數中對其進行初始化,則還需要在構造函數中初始化this.state

 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'; 不是國家管理的。

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

這應該可以工作,而不是更改顏色更新 backgroundColor 的值

一些帶有按鈕的工作代碼,用於添加正方形並選擇更改正方形的背景顏色。

工作代碼和框鏈接 - 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM