【问题标题】:React : setting scrollTop property of div doesn't work反应:设置 div 的 scrollTop 属性不起作用
【发布时间】:2019-04-15 08:05:20
【问题描述】:

我是新手,目前我正在尝试将 div 的 scrollTop 属性设置为所需的数字。不幸的是,它对我不起作用。请看下面的代码:

class Testdiv extends React.Component {
  constructor(props){
    super(props);
    this.divRef = React.createRef();
  }
  componentDidMount(){
    this.divRef.current.scrollTop = 100;
  }
  render(){
    return (
     <div className="testDiv" ref={this.divRef}>
      Hello World<br /><br /><br /><br />
        Hello World!
      </div>
    );
  }
}
ReactDOM.render(
 <Testdiv />,
 document.getElementById('root')
);

还有 CSS:

.testDiv{
  height: 500px;
  overflow: auto;
}

Here 是相应代码的代码笔。附言我不想使用 Jquery。谢谢你的帮助。

【问题讨论】:

    标签: javascript css html reactjs


    【解决方案1】:

    这是一个 css/溢出问题,而不是 JS/React 问题。问题是testDiv 不够高,无法发生任何事情。在上面设置height: 30px,你会看到区别:https://codepen.io/anon/pen/ZmBydZ

    【讨论】:

      【解决方案2】:

      你要确保testDiv的内容高于容器本身,并设置y轴溢出滚动。

      示例

      class Testdiv extends React.Component {
        divRef = React.createRef();
      
        componentDidMount() {
          setTimeout(() => {
            this.divRef.current.scrollTop = 1000;
          }, 1000);
        }
      
        render() {
          return (
            <div style={{ height: 200, overflowY: "scroll" }} ref={this.divRef}>
              Hello World
              <div style={{ height: 300 }} />
              Hello World!
            </div>
          );
        }
      }
      
      ReactDOM.render(<Testdiv />, document.getElementById("root"));
      <script src="https://unpkg.com/react@16.6.1/umd/react.production.min.js"></script>
      <script src="https://unpkg.com/react-dom@16.6.1/umd/react-dom.production.min.js"></script>
      
      <div id="root"></div>

      【讨论】:

      • 谢谢,它正在工作。但我不明白您所说的“testDiv 的内容高于容器本身”是什么意思。 testDiv 不是容器吗?
      • @anweshmohapatra 太棒了!在我的示例中,testDiv 容器的高度为 200 像素,但 testDiv 容器的子容器的总高度高于该容器的总高度,因为其中一个子容器的高度为 300 像素。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      相关资源
      最近更新 更多