在react中访问'scrollLeft'属性

问题描述 投票:0回答:1

当我把我的代码从基本的HTML和JS转换到response时,我遇到了一个div属性的问题。

旧代码和Desired结果将是这样的。

https:/codepen.iofadeomarprojecteditorDVWGjd。

现在,当开始将这个项目转换为react时,它不能改变scrollLeft属性的值。

我的问题是,如何才能改变 scrollLeft 在react中为某个元素设置事件监听器,我在搜索这个问题时得到的结果是为整个窗口对象设置事件监听器,而不是为DOM中的某个特定元素设置事件监听器

我想使用可重复使用的组件来实现拖动和滚动,下面是代码。

import React from 'react';
import PropTypes from 'prop-types';

export class ScrollDrag extends React.Component {
  constructor(props) {
    super(props);
    this.ref = React.createRef();
    this.state = {
      isScrolling: false,
      clientX: 0,
      scrollX: 0,
    };
  }

  onMouseDown = e => {
    this.setState({ ...this.state, isScrolling: true, 
     clientX: e.clientX });
  };

  onMouseUp = () => {
    this.setState({ ...this.state, isScrolling: false });
  };

  onMouseMove = e => {
    const { clientX, scrollX } = this.state;
    if (this.state.isScrolling) {
      this.ref.current.scrollLeft = scrollX + e.clientX - clientX;
      this.setState({scrollX: scrollX + e.clientX - clientX, clientX: e.clientX})
    }
  };

  render() {
    const { rootClass } = this.props;
    return (
      <div
        ref={this.ref}
        onMouseDown={this.onMouseDown}
        onMouseUp={this.onMouseUp}
        onMouseMove={this.onMouseMove}
        className={rootClass}
      >
        {React.Children.map(this.props.children, child =>
            React.Children.only(child))}
      </div>
    );
  }
}

ScrollDrag.defaultProps = {
  ref: { current: {} },
  rootClass: '',
};

ScrollDrag.propTypes = {
  ref: PropTypes.object,
  rootClass: PropTypes.string,
  children: PropTypes.string,
};

export default ScrollDrag;

然后,我把它作为应用程序中的继承订单组件使用

这是我的尝试。https:/codesandbox.iospeaceful-butterfly-ndp6z?

任何帮助,使这个工程是感激

javascript reactjs dom scroll drag
1个回答
0
投票

更新答案

你滚动了错误的元素。我删除了项目的包装纸并调整了CSS。我还不得不把滚动的极性反过来。现在它工作了。

https:/codesandbox.iosawesome-tree-s8miv?file=srcDragScroll.js。

原始问题的原始答案(现已编辑)。

该错误是由于你没有使用 ref 你在这个组件中创建的。

render() {
    const { ref, rootClass } = this.props; // <-- this is wrong
    return (
      <div
        ref={ref}
        onMouseDown={this.onMouseDown}
        onMouseUp={this.onMouseUp}
        onMouseMove={this.onMouseMove}
        className={rootClass}
      >
        {React.Children.map(this.props.children, child =>
            React.Children.only(child))}
      </div>
    );

应该是这样的

render() {
    const { rootClass } = this.props;
    return (
      <div
        ref={this.ref}
        onMouseDown={this.onMouseDown}
        onMouseUp={this.onMouseUp}
        onMouseMove={this.onMouseMove}
        className={rootClass}
      >
        {React.Children.map(this.props.children, child =>
            React.Children.only(child))}
      </div>
    );
© www.soinside.com 2019 - 2024. All rights reserved.