繁体   English   中英

React JS如何更改元素中的字体颜色而不是单击按钮onClick?

[英]React JS How to change font color in element other than clicked button onClick?

所以我设法在该按钮中使用 setState() 更改按钮的背景颜色。 但是,我正在尝试使用该按钮来更改同一组件中列表元素的字体颜色。

使用 setState() 只能让我更改我单击的元素。 我试过查询选择其他元素的 class,但使用 left.setState() 不是有效的 function。

如何使用按钮的 onClick function 更改元素的 CSS 属性?

import React, { Component } from 'react';
import firebase from 'firebase';
import { firebaseConfig } from './connection';

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
let messageRef = firebase.database().ref('messages');

class LandingPage extends Component {

  constructor(props) {
    super(props);

    this.state = {
      name: '',
      message: '',
      list: [],
      font: "black",
      color: "blue"
    }
  }

//   onChange = () => {
//     if (this.state.color == 'blue'){
//       this.setState({ color: 'green' });
//     }
//     else {
//       this.setState({ color: 'blue' });
//     }
//  }

 onChange = () => {
  var left = document.querySelectorAll(".left");
  if (this.state.color === 'black'){
    this.setState({ color: 'grey' });
  }
  else {
    this.setState({ color: 'black' });
  }
}

  render() {
    return <div className='container'>

      {/* title */}
      <div className='titleDiv'>
        <h1>React Message App</h1>
      </div>

      {/* messages will be listed here */}
      <div className='messagesDiv' id='messagesDivId'>
        <ul>
          {/* List array is mapped through*/}
          {this.state.list.map(item => {
            return (
              <li className={(item.name === this.state.name ? 'right' : 'left')}
              style={{ color: this.state.font }}
                key={item.id}
                id={item.id}>
                {item.name}: {item.message}
              </li>
            )
          })}
        </ul>
      </div>

      {/*think, delete options*/}

      <button className='button think' style={{ backgroundColor: this.state.color }} onClick={this.onChange}>Think...</button>

      <button className='button delete'>Delete last message</button>
    </div>
  }
}

export default LandingPage;

应该单击“思考”按钮以更改具有“左”或“右”class 名称的列表元素。 请指教...

你弄乱了一些变量名并误解了 React 的工作原理。

首先,您不能查询 HTML 元素并执行setState ,因为这是一个 React function。 无法从 HTML 文档中访问此 function。

其次,您通过单击按钮更改 state 变量并将此变量映射到列表元素的颜色的第一种方法是正确的,但是您混淆了名称:

这是你的onChangeMethod

onChange = () => {
    if (this.state.color == 'blue'){
        this.setState({ color: 'green' });
    }
    else {
        this.setState({ color: 'blue' });
    }
}

在这里,您将 state 变量映射到颜色属性:

<li className={(item.name === this.state.name ? 'right' : 'left')}
    style={{ color: this.state.font }}
    key={item.id}
    id={item.id}>
    {item.name}: {item.message}
</li>

您在onChange function 中设置state.color ,但您在列表元素中引用state.font ,而是将style更改为以下内容:

style={{ color: this.state.color }}

您需要绑定到 onChange 方法。 您可以像这样在构造函数方法中执行此操作:

constructor(props) {
super(props);

this.state = {
  name: '',
  message: '',
  list: [],
  font: "black",
  color: "blue"
}

this.onChange = this.onChange.bind(this)
}
import React, { Component } from "react";

class LandingPage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      list: [
        {
          id: "1",
          message: "Hello World 1"
        },
        {
          id: "2",
          message: "Hello World 2"
        },
        {
          id: "3",
          message: "Hello World 3"
        }
      ],
      color: "red"
    };
    this.onChange = this.onChange.bind(this);
  }

  onChange = () => {
    if (this.state.color == "red") {
      this.setState({ color: "green" });
    } else {
      this.setState({ color: "red" });
    }
  };

  render() {
    return (
      <div className="container">
        <div className="titleDiv">
          <h1>React Message App</h1>
        </div>

        <div className="messagesDiv" id="messagesDivId">
          <ul>
            {this.state.list.map(item => {
              return (
                <li
                  style={{ color: this.state.color }}
                  key={item.id}
                  id={item.id}
                >
                  {item.message}
                </li>
              );
            })}
          </ul>
        </div>

        <button className="button think" onClick={this.onChange}>
          Change Color
        </button>
      </div>
    );
  }
}

export default LandingPage;

检查这是否是你想要的?

如果你想尝试内联..

<button className='button think' style={{ backgroundColor: this.state.color }} onClick={()=>{this.state.this.state.color == 'blue'?this.setState({ color: 'green' }):this.setState({ color: 'blue' })}}>Think...</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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