是的,我想说在 React 中使用 jQuery 有一些缺点。
VDOM diffing 算法会混淆
这是你提到的。是的,如果您只使用 read-only 属性会很好,但除非您针对的是较旧的浏览器,否则 document.querySelector 的重量会更轻。
您引入的每个依赖项,尤其是像图书馆这样大的依赖项,都应该经过仔细审查。详情请见the website obesity epedemic。
此外,“我只将它用于阅读,让 React 完成其余工作”的想法会给您的代码增加一层明显的混乱,我们将在下一个示例中看到。
你放弃了 React 的模式
在我看来,更大的问题是放弃 React 的模式。用一句话来描述 React,我会说:
React 是一个基于组件的库,用于生成源自state 输入的 HTML、CSS 和 JavaScript 功能。
假设我有一个简单的UserProfile 组件。该组件将包含一些关于用户的数据,包括接收或不接收推送通知的开关:
// 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 为真,则复选框将被选中。
让我们用所提议的设计模式来看看这个相同的例子:
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 操作库来格式化它。
这是一个人为的例子,但每次我在现实生活中看到这个版本时,都会变得一团糟。
最后,为什么?
花点时间学习一下 React 设计模式。我建议thinking in React。 jQuery 应该是最后的手段,因为我认为您使用 React 是有原因的。
一个例外是你在 React 中使用的 jQuery 库
在这种情况下,除了重写库之外,您别无选择。正如this article 中强调的那样,您应该编写一个包装器组件以使其符合 React。