Created
August 16, 2018 11:16
-
-
Save 1natsu172/ab70c4f4d76d1261fabdf17b0a746d69 to your computer and use it in GitHub Desktop.
Reactでpulltorefreshjsを使いたかったので書いたラッパーコンポーネント
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { uniqueId } from 'lodash-es' | |
import PullToRefreshJS from 'pulltorefreshjs' | |
import * as React from 'react' | |
import { findDOMNode } from 'react-dom' | |
type Props = { | |
onRefresh: (() => Promise<any>) | (() => void) | |
children: React.ReactNode | |
targetComponent?: React.ReactInstance | |
} & Partial<DefaultProps> | |
type DefaultProps = Readonly<typeof defaultProps> | |
const defaultProps = { | |
disabled: false, | |
distanceFromTop: 0 | |
} | |
export default class PullToRefresh extends React.Component<Props> { | |
public static defaultProps = defaultProps | |
private elementId: string | |
private ptrInstance: any | |
constructor(props: Props) { | |
super(props) | |
this.elementId = uniqueId('ptr') | |
} | |
public componentDidMount() { | |
if (!this.props.disabled) this.setupPullToRefresh() | |
} | |
public componentDidUpdate(prevProps: Props) { | |
const isDisableToEnable = prevProps.disabled && !this.props.disabled | |
const isEnableToDisable = !prevProps.disabled && this.props.disabled | |
if (isDisableToEnable) this.setupPullToRefresh() | |
if (isEnableToDisable) this.ptrInstance.destroy() | |
} | |
public componentWillUnmount() { | |
this.ptrInstance.destroy() | |
} | |
public render() { | |
return <div id={this.elementId}>{this.props.children}</div> | |
} | |
private setupPullToRefresh() { | |
this.ptrInstance = PullToRefreshJS.init({ | |
mainElement: `#${this.elementId}`, | |
onRefresh: () => this.props.onRefresh(), | |
shouldPullToRefresh: () => { | |
const containerElement = findDOMNode(this) as Element | |
const targetComponent = findDOMNode( | |
this.props.targetComponent! | |
) as Element | |
if (containerElement && this.props.targetComponent) { | |
return targetComponent.scrollTop <= this.props.distanceFromTop! | |
} | |
if (containerElement) { | |
const { | |
top: distanceFromTop | |
} = containerElement.getBoundingClientRect() | |
return distanceFromTop <= this.props.distanceFromTop! | |
} | |
return !window.scrollY | |
}, | |
triggerElement: `#${this.elementId}` | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
loading中のアイコンとか文章がstringしか受け付けてなくてJSX.Element渡せないことに気づいたのでボツにした 🤔