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.

My Case is:

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>

using JQuery:

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

My Question:

我怎样才能用ReactJS做到这一点?

推荐答案

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 $(...)...
  }

  // ...
}

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 link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110 (I changed this link to https ^)

Jquery相关问答推荐

提交表单时运行自定义验证脚本

当我使用 OwlCarousel 时,没有任何显示

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

如何在 jquery 中切换 attr()

jQuery找到最近的匹配元素

jQuery $(document).ready () 触发两次

ASP .NET MVC 在每个字段级别禁用客户端验证

如何在使用 jQuery 单击特定链接时打开 bootstrap 导航选项卡的特定选项卡?

如何同时使用 requireJS 和 jQuery?

如何在 jQuery .each() 的每次迭代之间添加暂停?

jQuery ajax 在 asp.net mvc 中上传文件

datatable jquery - 表头宽度与正文宽度不对齐

使用 jquery 通过文本设置下拉值

$(document).ready(function(){});页面底部的 vs 脚本

删除除一个之外的所有类

$.ajax 的成功和 .done() 方法有什么区别

javascript,是否有像 isArray 这样的 isObject 函数?

fancybox2 / fancybox 导致页面跳转到顶部

Ajax 处理中的无效 JSON 原语

小于 10 给数字加 0