如何在ReactJS上使用JQuery [英] How to use JQuery on ReactJS

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

问题描述

我是ReactJS的新手。直到现在我正在使用JQuery来设置我需要的任何动画或某些功能。但现在我正在尝试使用ReactJS并使用JQuery进行最小化。

I'm newbie with ReactJS. Till now I'm using JQuery to set any animation or some feature that I needed. But now I'm trying to use ReactJS and minimalize using JQuery.

我的案例是:

我是尝试构建自己的手风琴,使用JQuery我可以做到,但是使用ReactJS我不知道怎么做。

My Case is:
I'm trying to build own accordion, with JQuery I can done it, but with ReactJS I don't get the idea how to.

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

我的问题:

1.如何在ReactJS中做到这一点?

My Question:
1. How to do that in ReactJS ?



谢谢之前


Thanks before

推荐答案

你应该试着避免在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 $(...)...
  }

  // ...
}

理想情况下,你想要创建一个可重复使用的Accordion组件。为此你可以使用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?editors=0110
(我更改了这个链接到https ^)

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

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

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