jQuery样式在React Component中不起作用
jquery styling not working in react component
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
}
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 监视函数从服务返回不起作用,但作用域函数起作用
- 幻灯片滚动javascript不起作用
- 简单的javascript在Shopify中不起作用
- Recaptcha在IE7和IE8中不起作用
- Ember Data DS.Model's set函数不起作用
- JsFiddle上的鼠标事件不起作用
- 我的AngularJS表达式没有'不起作用
- 点击按钮输入不起作用
- 面向对象的Javascript代码在IE7中不起作用
- 分部隐藏在jquery中不起作用
- 在phonegap应用程序内部重定向不起作用
- Array.length似乎不起作用;console.log则显示其他情况
- $ionicplatform内的$scope不;不起作用
- 我的javascript for循环不起作用
- Meteor-添加用户自定义字段的方法不起作用
- 为什么 .focus() 不起作用,而 .css(“color”,“red”) 在同一个选择器上起作用
- Textarea必需的attribut在javascript中不起作用
- jQuery样式在React Component中不起作用
- AngularJS .component()中的输出函数('&')不起作用