単純な反応フェードアニメーションフック


おいあなた!はいあなた!あなたの反応成分に迅速かつ簡単なフェードアニメーションが必要ですか?図書館を設置する気がしない?
次に行きましょう!💨💨💨

すでにコードを見せてください!👀
フックが戻る[isVisible, setVisible, fadeProps] , まさにuseState() フック、しかし、あなたも設定する必要がありますfadeProps あなたがフェードしたい要素に.
const MyFadingComponent = () => {
    // Just like useState() hook, the fadeProps go on the fading DOM element
    const [isVisible, setVisible, fadeProps] = useFade();

    // You can use isVisible to mount/unmount the component!
    return <>
        <button onClick={() => setVisible(!isVisible)}>Toggle visibility</button>
        {isVisible && <h2 {...fadeProps}>Now you see me...</h2>}
    </>;
};

フック!🎣
用途onAnimationEnd 設定を遅延するisVisible state to false , これにより、コンポーネントがアンマウント前にアニメーションを終了できます.
const useFade = (initial) => {
    const [show, setShow] = useState(initial);
    const [isVisible, setVisible] = useState(show);

    // Update visibility when show changes
    useEffect(() => {
        if (show) setVisible(true);
    }, [show]);

    // When the animation finishes, set visibility to false
    const onAnimationEnd = () => {
        if (!show) setVisible(false);
    };

    const style = { animation: `${show ? "fadeIn" : "fadeOut"} .3s` };

    // These props go on the fading DOM element
    const fadeProps = {
        style,
        onAnimationEnd
    };

    return [isVisible, setShow, fadeProps];
};

スタイル💅
@keyframes fadeIn {
    0% { opacity: 0; }
    100% { opacity: 1; }
}

@keyframes fadeOut {
    0% { opacity: 1; }
    100% { opacity: 0; }
}

ポイントは?🙄
我々が使用するならばuseState() フックのような表現で状態を適用するisVisible && <Component /> , 我々のコンポーネントは、CSSアニメーションが終了する前にアンマウントします.The useFade() フックがアニメーションを終了するまでアンマウントします.

何がこれについてクールですか?😎
構文はまさにuseState() , あなたは、単にisVisible && <Component /> コンポーネントをマウント/アンマウントする式.
ここではどのようにそれを行うReact Transition Group , あなたはラッパーのコンポーネントを必要とすると入力/終了アニメーションを自分で状態、Yuck!Framer Motion and React Spring は似ている.

改善のための部屋
つの要素間のトグルは、現時点では実際には動作しません.
const [isVisible, setVisible, fromProps, toProps] = useFade();

{isVisible ? <ComponentA {...fromProps} /> : <ComponentB {...toProps} />}
私は、反対のフェードアニメーションをComponentB , しかし、それを正しく取得する方法を把握することはできません.あなたが考えがあるならば、知らせてください!