简体   繁体   中英

react using jquery to 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>
        );
    }
});

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

Whats the correct way of binding "this [element]" so jQuery can do its slideToggling on it?

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

a second question that comes to mind: is it bad practice to use the jQuery.ready function to bind click events etc... with react?

theoretically I can bundle a jquery file with each component file with its event handlers.

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.

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>
  );
}

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.

In this case, we use it to create and expose a new this.toggle method, which calls .slideToggle on the element.

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM