web-dev-qa-db-ja.com

React refsを使用したscrollIntoView

ユーザーが別のコンポーネントを閉じたときに、特定のコンポーネントまでスクロールしようとしています。

この例は、下の例と非常によく似ています。 https://reactjs.org/docs/refs-and-the-dom.html#exposing-dom-refs-to-parent-components

_function CustomComponents(props) {
  const items = [1,2,3,4].map((x, i) => return (
    <div ref={props.inputRef} key={i}>
     x + hello
    </div>
  )

  return (
    <div>
      { items }
    </div>
  );
}

function Parent(props) {
  return (
    <div>
      <CustomComponents inputRef={props.inputRef} />
    </div>
  );
}


class Grandparent extends React.Component {
  render() {
    return (
      <Parent
        inputRef={el => this.inputElement = el}
      />
    );
  }
}
_

カードの大きなリストをレンダリングしており、this.refs[elem].scrollIntoView()を呼び出して特定のカードにスクロールできるようにしたい

しかし、問題は_this.refs_を呼び出すと、すべてのレベルで空のオブジェクトが返されるため、特定の要素にアタッチして、このコンポーネントを表示するためにユーザーが戻ったときに起動できないことです。

この問題をどのように解決するかについての助けが必要です。

10
Sohil Pandya

どこでthis.refs[elem].scrollIntoView()を呼び出そうとしていますか? refメソッド内ではなく、componentDidMountまたはcomponentDidUpdate内でrendersを操作する必要があります。

1
claireinez

私の祖父母コンポーネントに以下に記述されているifステートメントを提供することで、特定の問題を解決しました。

inputRef={el => { 
  if (el && el.id == this.state.selectedBuildingRef) {
    this.myelement.scrollIntoView();
    window.scrollBy(0, -65);
  } 
}}
0
Sohil Pandya