是的,我会说在React中使用jQuery有缺点。
的VDOM版本比较算法会感到困惑
这是一个你提到的。是的,如果您只使用read-only
属性,那么效果会很好,但除非您将目标锁定为旧版浏览器,否则document.querySelector
之类的内容重量更轻。
你要引入的每一个依赖,特别是像图书馆那样大的一个,应该仔细审查。详情请参阅the website obesity epedemic。我们将在下一个例子中看到,“我只会用它来阅读并让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
为true,则复选框将被选中。
让我们看看所提出的设计模式,这同例如:
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设计模式。我建议。 jQuery应该是最后的手段,因为你使用React是出于我假设的原因。
有一个例外,这是jQuery的库您使用阵营
在这种情况下,你有超过重写库中的其他没有其他选择。如this article中突出显示的那样,您应该编写一个包装组件来使其符合React。
如果你只想要jQuery的选择器引擎,请使用[Sizzle](https://sizzlejs.com/)或[Zepto](http://zeptojs.com/)来查看。如果您不担心向后兼容较旧的非常规浏览器,请尝试此解决方案(https://stackoverflow.com/questions/12980877/parents-without-jquery-or-queryselectorall-for-parents)。 – Terry
结帐https://sizzlejs.com/ –