jQuery样式在React Component中不起作用

jquery styling not working in react component

本文关键字:不起作用 Component React 样式 jQuery      更新时间:2023-09-26

jQuery似乎在反应组件中工作正常,但是,当我尝试在反应组件中使用jquery应用样式时,它不起作用。在下面的代码中,每个循环中的console.log(eachVisitedTopic)都按预期返回正确的结果。

topicsVisited(arr){
     $(function() {
      $.each(arr, function(key, eachVisitedTopic) {
        console.log(eachVisitedTopic);
        $('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
          'background-color': 'red'
        });
      });
    });
  };

标记

import {React, ReactDOM} from '../../../../build/react';
export default class SingleTopicBox extends React.Component {
  render() {
    return (
      <div>
        <div className="col-sm-2">
          <div className="single-topic" data-topic-id={this.props.topicID} onClick={() => this.props.onClick(this.props.topicID)}>
            {this.props.label}
            {this.props.topicID}
          </div>
        </div>
      </div>
    );
  }
};

React 应该处理所有的渲染,它检查脏的 dom 并只渲染更改的内容。

你可以实现你想要的,只需使用反应状态。当你触发一个setState更改时,反应会查看DOM,找到已经更改的内容,然后渲染它。

参考: https://facebook.github.io/react/docs/component-api.html#setstate

constructor() {
        super();
        this.state = {
            bgDisplayColor: "blue"
        };
    }  

然后你可以在 yout 组件中做这样的事情:

$('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
          'background-color': this.state.bgDisplayColor
        });

要更新它,您只需使用:

this.setState({bgDisplayColor: "red"});

编辑

要解决未定义的变量错误,您必须将"this"的作用域存储在函数中并使用而不是"this",因为在jquery.css中,"this"指的是Jquery,而不是实际类的"this"作用域。

例:

topicsVisited(arr){
   var self = this;
   $(function(){
      $.each(arr, function(key, eachVisitedTopic){
         console.log(eachVisitedTopic);
         //self here is the global scope of your class
         //Inside jQuery.css this refers to Jquery and not to your class.
         $('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
                  'background-color': self.state.bgDisplayColor
                });
        });
      });
    });
  };
尝试将所有

jQuery 代码放在 componentDidMount 中例如:

      componentDidMount() {
         //Your jQuery function goes here 
      }