要素までスクロールするにはどうすればいいですか? 質問する

要素までスクロールするにはどうすればいいですか? 質問する

スクロールアップするたびにメッセージの配列を表示するチャットウィジェットがあります。現在直面している問題は、メッセージが読み込まれるときにスライダーが上部に固定されたままになることです。前の配列の最後のインデックス要素にフォーカスを当てたいのですが、インデックスを渡すことで動的参照を作成できることがわかったのですが、それを実現するにはどのようなスクロール関数を使用するかを知る必要もあります。

 handleScrollToElement(event) {
    const tesNode = ReactDOM.findDOMNode(this.refs.test)
    if (some_logic){
      //scroll to testNode      
    }
  }

  render() {

    return (
      <div>
        <div ref="test"></div>
      </div>)
  }

ベストアンサー1

React 16.8 +、関数コンポーネント

const ScrollDemo = () => {
   const myRef = useRef(null)

   const executeScroll = () => myRef.current.scrollIntoView()    
   // run this function from an event handler or an effect to execute scroll 

   return (
      <> 
         <div ref={myRef}>Element to scroll to</div> 
         <button onClick={executeScroll}> Click to scroll </button> 
      </>
   )
}

StackBlitzの完全なデモを見るにはここをクリックしてください

React 16.3 +、クラスコンポーネント

class ReadyToScroll extends Component {
    constructor(props) {
        super(props)
        this.myRef = React.createRef()  
    }

    render() {
        return <div ref={this.myRef}>Element to scroll to</div> 
    }  

    executeScroll = () => this.myRef.current.scrollIntoView()
    // run this method to execute scrolling. 
}

クラスコンポーネント - Ref コールバック

class ReadyToScroll extends Component {  
    render() {
        return <div ref={ (ref) => this.myRef=ref }>Element to scroll to</div>
    } 

    executeScroll = () => this.myRef.scrollIntoView()
    // run this method to execute scrolling. 
}

文字列参照を使用しないでください。

文字列参照はパフォーマンスに悪影響を与え、構成不可能であり、廃止される予定です (2018 年 8 月)。

文字列参照にはいくつか問題があり、レガシーとみなされており、将来のリリースで削除される可能性があります。[公式 React ドキュメント]

リソース1リソース2

オプション: スムーズなスクロールアニメーション

/* css */
html {
    scroll-behavior: smooth;
}

子に参照を渡す

ref は react コンポーネントではなく dom 要素に添付する必要があります。そのため、子コンポーネントに渡すときに、prop ref に名前を付けることはできません。

const MyComponent = () => {
    const myRef = useRef(null)
    return <ChildComp refProp={myRef}></ChildComp>
} 

次に、ref プロパティを dom 要素に添付します。

const ChildComp = (props) => {
    return <div ref={props.refProp} />
}

おすすめ記事