簡體   English   中英

為什么這個反應按鈕在按下時不會改變 div 文本顏色?

[英]Why this react button is not changing the div text color when pressed?

我的問題是為什么這個按鈕在按下時沒有將 div 文本顏色更改為綠色?

這是代碼,希望對您幫助我解決這個疑問有用:

import React from 'react';
import hola from './hola.css'

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: props.color };
  }

  render() {
    return (
      <div style={{ color: this.state.color }}> Hello World! </div>
    )
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: 'red' };
  }

  render() {
    return (
      <div>
        <Child color={this.state.color} />
        <button onClick={() => this.setState({ color: 'green'})}>
          Change Color
        </button>
      </div>
    )
  }
}

export default App;

你的構造函數運行一次,你將它的初始值復制到 state 中,它永遠不會改變。 您在這里有兩個選擇:

  1. 將按鈕移動到組件中,使其設置組件自己的state:
render() {
  return (
    <>
      <div style={{ color: this.state.color }}> Hello World! </div>
      <button onClick={() => this.setState({ color: 'green'})}>
        Change Color
      </button>
  )
}
  1. 直接使用道具:
<div style={{ color: this.props.color }}> Hello World! </div>

暫無
暫無

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

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