如何在ReactJS中使用JQuery [英] How to use JQuery with ReactJS

查看:68
本文介绍了如何在ReactJS中使用JQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ReactJS的新手.以前,我使用jQuery设置所需的任何动画或功能.但是现在我正在尝试使用ReactJS并尽量减少使用jQuery.

I'm new to ReactJS. Previously I've used jQuery to set any animation or feature that I needed. But now I'm trying to use ReactJS and minimize the use of jQuery.

我的案子是:

我正在尝试使用ReactJS构建手风琴.

I'm trying to build an accordion with ReactJS.

<div class="accor">
   <div class="head">Head 1</div>
   <div class="body hide">Body 1</div>
</div>
<div class="accor">
   <div class="head">Head 1</div>
   <div class="body hide">Body 1</div>
</div>
<div class="accor">
   <div class="head">Head 1</div>
   <div class="body hide">Body 1</div>
</div>

使用jQuery :

$('.accor > .head').on('click', function(){
   $('.accor > .body').slideUp();
   $(this).next().slideDown();
});

我的问题:

如何使用ReactJS做到这一点?

How can I do this with ReactJS?

推荐答案

您应该尝试避免在ReactJS中使用jQuery.但是,如果您真的想使用它,则可以将其放入组件的componentDidMount()生命周期函数中.

You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.

例如

class App extends React.Component {
  componentDidMount() {
    // Jquery here $(...)...
  }

  // ...
}

理想情况下,您想创建一个可重用的手风琴组件.为此,您可以使用Jquery,也可以只使用普通的javascript + CSS.

Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.

class Accordion extends React.Component {
  constructor() {
    super();
    this._handleClick = this._handleClick.bind(this);
  }

  componentDidMount() {
    this._handleClick();
  }

  _handleClick() {
    const acc = this._acc.children;
    for (let i = 0; i < acc.length; i++) {
      let a = acc[i];
      a.onclick = () => a.classList.toggle("active");
    }
  }

  render() {
    return (
      <div 
        ref={a => this._acc = a} 
        onClick={this._handleClick}>
        {this.props.children}
      </div>
    )
  }
}

然后您可以在任何组件中使用它,如下所示:

Then you can use it in any component like so:

class App extends React.Component {
  render() {
    return (
      <div>
        <Accordion>
          <div className="accor">
            <div className="head">Head 1</div>
            <div className="body"></div>
          </div>
        </Accordion>
      </div>
    );
  }
}

此处的Codepen链接: https://codepen.io/jzmmm/pen/JKLwEA?编辑者= 0110 (我将此链接更改为https ^)

Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110 (I changed this link to https ^)

这篇关于如何在ReactJS中使用JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆