使用React的jQuery选择器可以吗? [英] jQuery Selectors with React is ok?

查看:91
本文介绍了使用React的jQuery选择器可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道混合jQuery和ReactJS是不可取的,因为ReactJS不知道jQuery对DOM做出的任何修改。但是,如果您只使用jQuery查询DOM并轻松方便地查找节点,同时将所有DOM编辑保留到ReactJS,那该怎么办?除了jQuery是一个大型库,还有其他任何缺点吗?

I know mixing jQuery and ReactJS is not advisable, because ReactJS is not aware of any modifications to the DOM made by jQuery. But what if you only use jQuery for querying the DOM and finding nodes easily and conveniently, while leaving all the DOM editing to ReactJS. Other than jQuery being a big library, are there any other downsides to this?

一个示例用例是每当下拉菜单组件安装该检查以查看时设置事件监听器如果用户单击菜单上的任何位置,则菜单可以关闭。 jQuery .parents()方法是一种非常方便的方法,用于检查点击目标是否是菜单容器元素的子项。有没有一种简单的方法在 ReactJS vanilla JavaScript 中执行此操作?

An example use case is setting up event listeners whenever a dropdown menu component mounts that check to see if the user clicks anywhere off the menu, so that the menu can close. The jQuery .parents() method is a very convenient way to check if the the click target is a child of the menu container element. Is there an easy way to do this in ReactJS or with vanilla JavaScript?

以下是此示例的代码示例:

Here is a code sample of this example:

handleClick = e => {
  const element = $(e.target)
  if( !( element.parents('.menu').length || element.hasClass('menu'))) {
    this.setState({ menuOpen: false })
  }
}

componentWillUpdate (nextProps, nextState) {
  if(nextState.menuOpen && !this.state.menuOpen) {
    document.addEventListener('click', this.handleClick, false)
  } else if (!nextState.menuOpen && this.state.menuOpen) {
    document.removeEventListener('click', this.handleClick, false)
  }
}


推荐答案

是的,我想说在React中使用jQuery有一些缺点。

Yes, I would say there are disadvantages to using jQuery in React.

VDOM差异算法会混淆

这是你提到的。是的,如果您只使用只读属性,那就没问题,但除非您将旧版浏览器定位为 document.querySelector 重量会更轻。

This is one that you mentioned. Yes, it will be fine if you use only read-only attributes, but unless you're targeting older browsers something like document.querySelector would be lighter weight.

你所带来的每一个依赖,特别是像图书馆这样大的依赖,都应该经过仔细的审查。有关详细信息,请参见网站肥胖症大流行

Every depedency you're bringing in, especially as one as large as library, should be meticulously vetted. See the website obesity epedemic for details.

此外,我只会用它来阅读并让React完成剩下的工作的想法会给你的代码增加一层混乱,我们将在下一个例子中看到。

In addition, the idea of "I will only use it for reading and let React do the rest" will add a significant layer of confusion to your code, as we'll see in the next example.

你放弃了React的模式

在我看来,更大的问题是放弃模式反应。用一句话来形容React,我会说:

In my opinion, the bigger issue is abandoning the patterns of React. To describe React in one sentence, I would say:

React是一个基于组件的库,用于生成源自<$的HTML,CSS和JavaScript功能c $ c>州输入。

假设我有一个简单的 UserProfile 组件。此组件将包含有关用户的一些数据,包括用于接收推送通知的开关:

Let's say I have a simple UserProfile component. This component will have some data about the user, including a switch to receive push notifications or not:

// Please note this is simplified pseudo-code, and will likely not work
class UserProfile extends Component {
  state = {
    name: 'Bob',
    profilePic: 'someurl.com/profile-pic',
    isReceivingNotifications: false
  }

  updateReceivingNotifications = () => {
    this.setState({ isReceivingNotifications: !this.state.isReceivingNotifications })
  }

  render() {
    const { name, profilePic, isReceivingNotifcations } = this.state;
    return (
      <div>
        <h2>{name}</h2>
        <img src={profilePic} />
        <input type="checkbox" checked={isReceivingNotifications} onChange={this.updateReceivingNotifications} />
      </div>
    );
  }
}

简单,组件演示源自状态组件。如果 isReceivingNotifcations 为true,则将选中该复选框。

Simple, the component presentation is derived from the state of the component. If the isReceivingNotifcations is true, then the checkbox will be checked.

让我们看看这个与提议相同的例子设计模式:

Let's look at this same example with the proposed design pattern:

class UserProfile extends Component {
  state = {
    name: 'Bob',
    profilePic: 'someurl.com/profile-pic',
    isReceivingNotifications: false
  }

  componentDidMount() {
    const checkBox = document.getElementById('my-checkbox');
    const that = this;
    // Use a regular function to bind the this context to the checkbox instead of component
    checkBox.addEventListener('change', function() {
      if (this.checked) {
         that.setState({ isReceivingNotifcations: true });
      } else {
         that.setState({ isReceivingNotifcations: false });
      }
    });
  }

  render() {
    const { name, profilePic, isReceivingNotifcations } = this.state;
    return (
      <div>
        <h2>{name}</h2>
        <img src={profilePic} />
        <input
          type="checkbox"
          checked={isReceivingNotifications}
          id="my-checkbox"
          />
       </div>
    );
  }
}

无论格式如何,第一个都更清晰这可以使用jQuery或者你可以使用的任何DOM操作库。

The first is much cleaner, no matter how you format this with jQuery or whatever DOM manipulation library you would use.

这是一个人为的例子,但每次我在现实生活中看到它的某些版本时它都是相当的一团糟。

This is a contrived example, but every time I've seen some version of this in real life it's been quite a mess.

最后,为什么?

请稍等一下时间和学习反应设计模式。我建议在React中思考。 jQuery应该是最后的选择,因为你出于某种原因使用React。

Just take a bit of time and learn React design patterns. I'd suggest thinking in React. jQuery should be a last resort, as you're using React for a reason i'd assume.

一个例外是你在React中使用的jQuery库

在这种情况下,除了重写库之外,您没有其他选择。正如本文中所强调的那样,您应该编写一个包装器组件来制作它符合React。

In this case, you have no other option other than rewriting the library. As highlighted in this article you should write a wrapper component to make it React compliant.

这篇关于使用React的jQuery选择器可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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