问题描述
我正在尝试通过制作带有可折叠项目的菜单来学习一些React。我正在使用jQuery作为其slideToggle函数,但我无法使其正常工作。
I'm trying to learn some React by making a menu with collapsable items. I'm using jQuery for its slideToggle function but I cant get it to work right.
反应代码的相关部分是:
the relevant part of the react code is this:
var CollapsableMenuItem = React.createClass({
toggleDescription: function(el) {
$(el).slideToggle();
},
render: function() {
return (
<li>
<label className='title'
onClick={this.toggleDescription.bind(this)}>
{this.props.item.title}
</label>
<div className='description'>
<label>
{this.props.item.body}
</label>
</div>
</li>
);
}
});
虽然我正在试图滑动切换这个,这将需要在将来改变to
althought I'm currently trying to slide toggle "this", that will need to change in the future to
$(el).parent().find('.description').slideToggle();
因为这是需要滑动切换的实际元素
because that's the actual element that needs to slide toggle
什么是绑定this [element]的正确方法,所以jQuery可以对它进行slideToggling吗?
Whats the correct way of binding "this [element]" so jQuery can do its slideToggling on it?
我目前正在使用,还有其他一些你可以忽略的东西。相关代码位于javascript部分的底部
I'm currently working out of this fiddle, theres some other stuff in there you can ignore. The relevant code is at the bottom of the javascript section
第二个问题浮现在脑海中:使用jQuery.ready函数绑定点击事件等是不好的做法...有反应?
a second question that comes to mind: is it bad practice to use the jQuery.ready function to bind click events etc... with react?
理论上我可以将每个组件文件的jquery文件与其事件处理程序捆绑在一起。
theoretically I can bundle a jquery file with each component file with its event handlers.
推荐答案
React中的 this
的上下文不是元素,它是React组件。 jQuery不理解如何将它用作选择器。
The context of this
in React isn't the element, it's the React component. jQuery doesn't understand how to use it as a selector.
你需要获得你想用jQuery控制的元素的引用。
You'll need to get a reference to the element you want to control with jQuery.
makeTogglable: function(element) {
$element = $(element);
this.toggle = function() {
$element.slideToggle();
};
},
render: function() {
return (
<li>
<label onClick={this.toggle}></label>
<div ref={this.makeTogglable}></div>
</li>
);
}
进行回调,该回调将在安装组件时运行。 DOM元素将被传递给回调,以便您可以直接使用它。
The ref prop takes a callback, which will run when the component is mounted. The DOM element will be passed to the callback, so that you can work with it directly.
在这种情况下,我们使用它来创建和公开新的 this.toggle
方法,在元素上调用 .slideToggle
。
In this case, we use it to create and expose a new this.toggle
method, which calls .slideToggle
on the element.
最后,我们将新的 this.toggle
方法传递给我们想要触发的元素的 onClick
处理程序切换。在这种情况下,它是< div>
。
Finally, we pass the new this.toggle
method to the onClick
handler for the element that we want to trigger the toggle. In this case it's the <div>
.
这篇关于使用jquery对slideToggle做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!