是的,我會說在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/ –