scrollIntoView使用React引用

Soh*_*dya 10 javascript dom ref reactjs react-dom

我们正在尝试在用户关闭另一个组件时滚动到特定组件.

我们的示例与下面的示例非常类似,取自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}
      />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我们正在提供大量的卡片,并希望能够通过调用滚动到特定的卡片 this.refs[elem].scrollIntoView()

但我们的问题是调用this.refs在所有级别返回一个空对象,因此我们无法附加到特定元素,然后在用户返回查看此组件时触发它.

想要一些人如何解决这个问题.

小智 1

您想打电话到哪里this.refs[elem].scrollIntoView()?您应该在或内部使用refs ,而不是在方法内部。componentDidMountcomponentDidUpdaterender