LoginSignup
0
0

【ReactNative】自動スクロールと非同期処理

Posted at

やりたかったこと

アラーム時間指定画面(ShowPicker)を表示させた後、画面最下部に自動スクロールさせる動作の実装

ダウンロード.gif

詰まったこと

1回目のタップ時には、自動スクロールせず、2回目からはスクロールでぉた。

ポイント

React Nativeがコンポーネントをレンダリングする際、通常は非同期のプロセスだそう。
そのため、修正前のコードでは、ShowPickerのレンダリング中に、末尾自動スクロールが動いてしまった。

setTimeoutを使うことで、前のレンダリングが終わった後に次のコードが読み込まれるため、
ShowPickerのレンダリング後に、末尾自動スクロールが起き、ShowPickerの最下部にスクロールされるようになった。

■修正前

  const showDateTimePicker = (index) => {
    setShowPicker(true);
    setEditedAlarmIndex(index);

    scrollViewRef.current.scrollToEnd({ animated: true });

// DateTimePickerが表示されたときにスクロールを一番下にする
    if (scrollViewRef.current) {
      scrollViewRef.current.scrollToEnd({ animated: true });
    }
  };

■修正後

const showDateTimePicker = (index) => {
  setShowPicker(true);
  setEditedAlarmIndex(index);

  // DateTimePickerがレイアウトされた後に末尾にスクロール
  setTimeout(() => {
    if (scrollViewRef.current) {
      scrollViewRef.current.scrollToEnd({ animated: true });
    }
  }, 0);
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0