【问题标题】:Set class dynamically using classNames module not working使用 classNames 模块动态设置类不起作用
【发布时间】:2018-08-12 16:05:48
【问题描述】:

提前感谢您查看此内容。我正在尝试将我的元素的页面加载类设置为待处理,然后单击 onClick,删除待处理的类并添加已完成的类:

目前,已完成和待处理的状态相应发生变化;但是,课程不会改变(待定课程仍然是活动的,而完成的课程是不活动的)。任何帮助将不胜感激!

import React, { Component } from 'react';
import classNames from 'classnames';
import '../stylesheets/Task.css';

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

    this.state = {
      completed: false,
      pending: true
    }

    this.makeComplete = this.makeComplete.bind(this);
  }

  makeComplete() {
    if (this.state.pending) {
      this.setState({
        completed: true,
        pending: false
      }, () => {
        console.log('completed: ' + this.state.completed, '\npending: ' + this.state.pending);
      });
    }
  }

  render() {
    return (
      <div className="task">
        <div className="check-task-container" onClick={this.makeComplete} >
          <i className={classNames({
            completed: this.state.completed,
            pending: this.state.pending,
            far: true,
            'fa-circle': true
        })} ></i>
        </div>
        {this.props.title}
      </div>
    );
  }
}

【问题讨论】:

  • 只是想澄清一下:已完成和待处理的状态正在按预期变化;但是,i 元素上的类不会改变。

标签: reactjs class dynamic class-names


【解决方案1】:

如果我理解正确,您需要在 Event onClick 上更改 className。

如果是这样,请在 makeComplete 中更改您的 setState,如下所示:

this.setState({
        completed: !this.state.completed,
        pending: !this.state.pending
      });

this.setState((prevState) => {
  return {completed: !prevState.completed, pending: !prevState.pending};
});

working demo中的完整代码

【讨论】:

  • 谢谢 Jayavel - 我很欣赏这个演示;但是,它似乎不起作用。我的状态发生了变化;但是,i 元素上的类不会改变。
【解决方案2】:

这个问题确实与 i 元素到 svg 的字体转换有关,因为 React 在渲染时不知道元素的变化。为了解决这个问题,我不得不使用 fontawesome 节点模块 (https://www.npmjs.com/package/@fortawesome/react-fontawesome) 而不是使用 fontawesome CDN。

【讨论】:

    猜你喜欢
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多