hooks: extract element remaining view port height logic into a hook

This commit is contained in:
Haishan 2019-01-13 23:15:54 +08:00
parent 61dd81d488
commit fa7e03b926
2 changed files with 30 additions and 16 deletions

View file

@ -13,6 +13,7 @@ import { FixedSizeList as List, areEqual } from 'react-window';
import ContentHeader from 'c/ContentHeader';
import Rule from 'c/Rule';
import RuleSearch from 'c/RuleSearch';
import useRemainingViewPortHeight from '../hooks/useRemainingViewPortHeight';
import { getRules, fetchRules, fetchRulesOnce } from 'd/rules';
@ -45,24 +46,10 @@ const Row = memo(({ index, style, data }) => {
export default function Rules() {
const { fetchRulesOnce, fetchRules } = useActions(actions);
const { rules } = useStoreState(mapStateToProps);
const refRulesContainer = useRef(null);
const [containerHeight, setContainerHeight] = useState(200);
function _updateContainerHeight() {
const { top } = refRulesContainer.current.getBoundingClientRect();
setContainerHeight(window.innerHeight - top - paddingBottom);
}
const updateContainerHeight = useCallback(_updateContainerHeight, []);
useEffect(() => {
fetchRulesOnce();
}, []);
useLayoutEffect(() => {
updateContainerHeight();
window.addEventListener('resize', updateContainerHeight);
return () => {
window.removeEventListener('resize', updateContainerHeight);
};
}, []);
const [refRulesContainer, containerHeight] = useRemainingViewPortHeight();
return (
<div>
@ -70,7 +57,7 @@ export default function Rules() {
<RuleSearch />
<div ref={refRulesContainer} style={{ paddingBottom }}>
<List
height={containerHeight}
height={containerHeight - paddingBottom}
width="100%"
itemCount={rules.length}
itemSize={80}

View file

@ -0,0 +1,27 @@
import { useState, useRef, useLayoutEffect, useCallback } from 'react';
/**
* cosnt [ref, remainingHeight] = useRemainingViewPortHeight();
*
* return a reference, and the remaining height of the referenced dom node
* to the bottom of the view port
*
*/
export default function useRemainingViewPortHeight() {
const refRulesContainer = useRef(null);
const [containerHeight, setContainerHeight] = useState(200);
function _updateContainerHeight() {
const { top } = refRulesContainer.current.getBoundingClientRect();
setContainerHeight(window.innerHeight - top);
}
const updateContainerHeight = useCallback(_updateContainerHeight, []);
useLayoutEffect(() => {
updateContainerHeight();
window.addEventListener('resize', updateContainerHeight);
return () => {
window.removeEventListener('resize', updateContainerHeight);
};
}, []);
return [refRulesContainer, containerHeight];
}