-
Notifications
You must be signed in to change notification settings - Fork 0
[2020-02-02]React with Waypoint和其他 #38
Description
學習重點
學會引入waypoint的語法
最近的React專案需要使用Waypoint。過往有過使用Waypoint的經驗,所以並不擔心�使用失敗的情況發生。結果,在引入時,卻問題叢生。
簡單描述一下我遇到的情況以及我的解決辦法:
根據Waypoint官網使用npm install waypoints載入waypoints,並在我的App.js透過以下語法引入Waypoints
import Waypoints from 'waypoints/lib/noframework.waypoints.min'
初始化Waypoints
let waypoint = new Waypoint({
element: document.getElementById('waypoint'),
handler: function(direction) {
console.log('Scrolled to waypoint!')
}
})
出現問題如下:
Uncaught TypeError: n(...) is not a constructor
問題情況類似此StackOverflow貼文
在此貼文的comment欄位找到此資訊:
The noframework.waypoints.js file doesn't export or return anything so you can't assign the return value from require to Waypoint. It does add Waypoint to window though
基於此資訊,我將我的程式碼改動如下:
引入:
import 'waypoints/lib/noframework.waypoints.min'
useEffect(() => {
function handleAnimation() {
new window.Waypoint({
element: document.querySelector('.isAnimated'),
handler: function () {
this.element.classList.add('animated', 'fadeInUp')
},
offset:'20%'
})
}
window.addEventListener('load', handleAnimation)
return () => {
window.removeEventListener('load', handleAnimation)
};
}, [])
解釋:不要將assign Waypoint 到一個變數,因為他沒有return anything。在這邊我直接使用new constructor新產生一個window.Waypoint,並在其後添加參數。
會使用useEffect的原因是,在網頁load完後,Waypoint跳出錯誤訊息,表示沒有抓取到任何符合條件的elements,於是我使用useEffect設置了事件監聽器,確保網頁載入完成後,Waypoint才觸發。
可是這又產生一個新個問題,我的waypoint怎樣就是只會抓取到一個element,這就代表說我沒辦法達成在畫面捲動到特定elements時才觸發animation這件事。
這問題我還在思考該如何解決。還是只能使用針對react開發的waypoint才有辦法解決這個問題呢?
關於grid-gap:
The grid-gap property applies only between grid items. It never applies between a grid item and the grid container.
grid-gap只會指定grid-items之間的距離,換句話說,他不像是在grid-item上設置margin,最後要抓取最後一個grid-item,把其margin消除。這是使用grid-gap的優點之一。
指定function預設參數:
function multiply(a, b = 1) {
return a * b;
}