【问题标题】:jquery styling not working in react componentjquery样式在反应组件中不起作用
【发布时间】:2016-02-15 13:56:13
【问题描述】:

jQuery 似乎在 react 组件中运行良好,但是,当我尝试在 react 组件中使用 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>
    );
  }
};

【问题讨论】:

  • 你能举一个你的反应标记的例子吗?
  • 我认为您应该为此使用style 属性。这是处理样式状态的更强大的方法。
  • @FatihErikli 我已经添加了标记,您能否为我的案例展示一个示例。

标签: javascript jquery css reactjs


【解决方案1】:

React 应该处理所有的渲染,它会检查脏 dom 并只渲染发生变化的东西。

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

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

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

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

$('.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
                });
        });
      });
    });
  };

【讨论】:

  • 我收到Uncaught TypeError: Cannot read property 'bgDisplayColor' of undefined
  • 你可能在jquery的范围内,我会在编辑中发布解决方案。
【解决方案2】:

尝试将所有 jQuery 代码放在 componentDidMount 中 例如:

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

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 1970-01-01
    • 2017-12-03
    • 2017-02-16
    • 2023-03-06
    • 1970-01-01
    • 2021-09-16
    • 2022-01-13
    • 1970-01-01
    相关资源
    最近更新 更多