programing

리액트JS에 표시되도록 div를 스크롤하려면 어떻게 해야 합니까?

javajsp 2023. 2. 23. 22:01

리액트JS에 표시되도록 div를 스크롤하려면 어떻게 해야 합니까?

.div로 나열되는 입니다.div 표시되어 있는 하기 위해 했습니다. 현재 강조 표시되어 있는 어린이를 변경하기 위해 키보드 네비게이션을 추가했습니다.

지금은 키를 몇 번 눌러도 강조 표시된 항목이 표시되지 않습니다.뷰가 스크롤된 경우에도 위 키와 같은 현상이 발생합니다.

올바른 입니까?div야에넣??? ??

은 .List 및 의 '컴포넌트'Item요소.한 프로젝트에서는 아이템이 활성화되었는지 여부를 알려주는 방법을 사용했습니다. 아이템은 필요에 따라 목록을 스크롤하여 보기로 표시합니다.다음의 의사 코드에 대해 검토합니다.

class List extends React.Component {
  render() {
    return <div>{this.props.items.map(this.renderItem)}</div>;
  }

  renderItem(item) {
    return <Item key={item.id} item={item}
                 active={item.id === this.props.activeId}
                 scrollIntoView={this.scrollElementIntoViewIfNeeded} />
  }

  scrollElementIntoViewIfNeeded(domNode) {
    var containerDomNode = React.findDOMNode(this);
    // Determine if `domNode` fully fits inside `containerDomNode`.
    // If not, set the container's scrollTop appropriately.
  }
}

class Item extends React.Component {
  render() {
    return <div>something...</div>;
  }

  componentDidMount() {
    this.ensureVisible();
  }

  componentDidUpdate() {
    this.ensureVisible();
  }

  ensureVisible() {
    if (this.props.active) {
      this.props.scrollIntoView(React.findDOMNode(this));
    }
  }
}

더 나은 해결책은 항목이 목록에 있다는 것을 인식하지 않고 항목을 보기로 스크롤하는 것을 목록으로 만드는 것입니다. , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,ref특정 항목에 대한 속성을 지정하고 해당 항목과 함께 찾습니다.

class List extends React.Component {
  render() {
    return <div>{this.props.items.map(this.renderItem)}</div>;
  }

  renderItem(item) {
    var active = item.id === this.props.activeId;
    var props = {
      key: item.id,
      item: item,
      active: active
    };
    if (active) {
      props.ref = "activeItem";
    }
    return <Item {...props} />
  }

  componentDidUpdate(prevProps) {
    // only scroll into view if the active item changed last render
    if (this.props.activeId !== prevProps.activeId) {
      this.ensureActiveItemVisible();
    }
  }

  ensureActiveItemVisible() {
    var itemComponent = this.refs.activeItem;
    if (itemComponent) {
      var domNode = React.findDOMNode(itemComponent);
      this.scrollElementIntoViewIfNeeded(domNode);
    }
  }

  scrollElementIntoViewIfNeeded(domNode) {
    var containerDomNode = React.findDOMNode(this);
    // Determine if `domNode` fully fits inside `containerDomNode`.
    // If not, set the container's scrollTop appropriately.
  }
}

항목이 목록 노드 내에 표시되는지 여부를 계산하지 않으려면 DOM 메서드 또는 웹킷별 방법을 사용할 수 있습니다.scrollIntoViewIfNeeded폴리필을 사용할 수 있으므로 웹킷 이외의 브라우저에서도 사용할 수 있습니다.

React 16의 경우 정답은 이전 답변과 다릅니다.

class Something extends Component {
  constructor(props) {
    super(props);
    this.boxRef = React.createRef();
  }

  render() {
    return (
      <div ref={this.boxRef} />
    );
  }
}

스크롤하려면 (컨스트럭터 뒤에)를 추가합니다.

componentDidMount() {
  if (this.props.active) { // whatever your test might be
    this.boxRef.current.scrollIntoView();
  }
}

주의: '.current'를 사용해야 하며 스크롤인토뷰 옵션을 전송할 수 있습니다.

scrollIntoView({
  behavior: 'smooth',
  block: 'center',
  inline: 'center',
});

(http://www.albertgao.xyz/2018/06/07/scroll-a-not-in-view-component-into-the-the-view-using-react/에서 찾을 수 있습니다.)

스펙을 읽어보니 블록과 인라인의 의미를 파악하기 어려웠지만, 그것을 가지고 놀다 보니 수직 스크롤 리스트의 경우 블록: '끝'이 뷰포트에서 콘텐츠 상단을 인위적으로 스크롤하지 않고 요소가 보이는 것을 알 수 있었습니다.'중앙'을 사용하면 하단 근처의 요소가 너무 멀리 미끄러져 올라가고 그 아래에 빈 공간이 나타납니다.하지만 제 컨테이너는 행동에 영향을 미칠 수 있도록 '스트레치'라는 정당성을 가진 유연한 부모입니다.더 이상 파고들지는 않았어요.오버플로우가 숨겨져 있는 요소는 스크롤인토뷰의 동작에 영향을 미치기 때문에 직접 시험해 봐야 합니다.

내 응용 프로그램에는 표시에 있어야 하는 부모가 있으며, 자녀가 선택되면 화면에도 스크롤됩니다.이는 부모 DidMount가 자녀의 DidMount보다 먼저 발생하므로 잘 작동하므로 부모로 스크롤되고 활성 자녀가 렌더링되면 더 스크롤하여 해당 DidMount를 볼 수 있습니다.

문자열이 아닌 참조에서 함수를 사용하는 또 다른 예제

class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items:[], index: 0 };
    this._nodes = new Map();

    this.handleAdd = this.handleAdd.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
   }

  handleAdd() {
    let startNumber = 0;
    if (this.state.items.length) {
      startNumber = this.state.items[this.state.items.length - 1];
    }

    let newItems = this.state.items.splice(0);
    for (let i = startNumber; i < startNumber + 100; i++) {
      newItems.push(i);
    }

    this.setState({ items: newItems });
  }

  handleRemove() {
    this.setState({ items: this.state.items.slice(1) });
  }

  handleShow(i) {
    this.setState({index: i});
    const node = this._nodes.get(i);
    console.log(this._nodes);
    if (node) {
      ReactDOM.findDOMNode(node).scrollIntoView({block: 'end', behavior: 'smooth'});
    }
  }

  render() {
    return(
      <div>
        <ul>{this.state.items.map((item, i) => (<Item key={i} ref={(element) => this._nodes.set(i, element)}>{item}</Item>))}</ul>
        <button onClick={this.handleShow.bind(this, 0)}>0</button>
        <button onClick={this.handleShow.bind(this, 50)}>50</button>
        <button onClick={this.handleShow.bind(this, 99)}>99</button>
        <button onClick={this.handleAdd}>Add</button>
        <button onClick={this.handleRemove}>Remove</button>
        {this.state.index}
      </div>
    );
  }
}

class Item extends React.Component
{
  render() {
    return (<li ref={ element => this.listItem = element }>
      {this.props.children}
    </li>);
  }
}

데모: https://codepen.io/anon/pen/XpqJVe

@Michelle Tilley의 답변을 바탕으로 사용자의 선택이 바뀌면 스크롤을 하고 싶을 때가 있기 때문에 스크롤을 트리거합니다.componentDidUpdate또한 스크롤의 범위와 스크롤이 필요한지 여부를 계산하기 위해 몇 가지 계산을 했습니다.이 계산은 다음과 같습니다.

  componentDidUpdate() {
    let panel, node;
    if (this.refs.selectedSection && this.refs.selectedItem) {
      // This is the container you want to scroll.          
      panel = this.refs.listPanel;
      // This is the element you want to make visible w/i the container
      // Note: You can nest refs here if you want an item w/i the selected item          
      node = ReactDOM.findDOMNode(this.refs.selectedItem);
    }

    if (panel && node &&
      (node.offsetTop > panel.scrollTop + panel.offsetHeight || node.offsetTop < panel.scrollTop)) {
      panel.scrollTop = node.offsetTop - panel.offsetTop;
    }
  }

반응 후크 포함:

  1. 수입품
import ReactDOM from 'react-dom';
import React, {useRef} from 'react';
  1. 새 후크 만들기:
const divRef = useRef<HTMLDivElement>(null);
  1. 새 Div 추가
<div ref={divRef}/>
  1. 스크롤 기능:
const scrollToDivRef  = () => {
    let node = ReactDOM.findDOMNode(divRef.current) as Element;
    node.scrollIntoView({block: 'start', behavior: 'smooth'});
}

혹시 누가 비틀거릴까 봐 이렇게 했어요.

  componentDidMount(){
    const node = this.refs.trackerRef;
    node && node.scrollIntoView({block: "end", behavior: 'smooth'})
  }
  componentDidUpdate() {
    const node = this.refs.trackerRef;
    node && node.scrollIntoView({block: "end", behavior: 'smooth'})
  }

  render() {
    return (

      <div>
        {messages.map((msg, index) => {
          return (
            <Message key={index} msgObj={msg}
              {/*<p>some test text</p>*/}
            </Message>
          )
        })}

        <div style={{height: '30px'}} id='#tracker' ref="trackerRef"></div>
      </div>
    )
  }

scrollIntoView네이티브 DOM 기능 링크

그것은 항상 보여질 것이다.tracker나누다

키 업/다운 핸들러에서는, 다음의 설정을 실시할 필요가 있습니다.scrollTop스크롤할 div의 속성을 눌러 아래로(또는 위로) 스크롤합니다.

예를 들어 다음과 같습니다.

JSX:

<div ref="foo">{content}</div>

키 업/다운 핸들러:

this.refs.foo.getDOMNode().scrollTop += 10

위와 유사한 작업을 수행하면 div가 10픽셀 아래로 스크롤됩니다(div가 오버플로로 설정되어 있는 경우).auto또는scroll물론 콘텐츠는 넘칩니다).

이를 확장하여 스크롤 div 내에서 div를 아래로 스크롤하고 싶은 요소의 오프셋을 찾은 후 수정해야 합니다.scrollTop높이를 기준으로 요소를 볼 수 있을 만큼 멀리 스크롤할 수 있습니다.

MDN의 scroll Top 정의와 오프셋을 소개합니다.맨 위:

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

React에서 Scroll-To 기능을 찾는 다른 사용자를 위해 정보를 추가합니다.앱용 스크롤 투를 실행하기 위해 여러 라이브러리를 연결했는데, 리액트 스크롤러를 찾을 때까지 어떤 라이브러리도 작동하지 않았기 때문에 넘겨야겠다고 생각했습니다.https://github.com/bySabi/react-scrollchor

NavLink를 클릭하면 이름 있는 앵커처럼 해당 요소로 스크롤됩니다.저는 이렇게 구현했습니다.

 <NavLink onClick={() => this.scrollToHref('plans')}>Our Plans</NavLink>
  scrollToHref = (element) =>{
    let node;
    if(element === 'how'){
      node = ReactDom.findDOMNode(this.refs.how);
      console.log(this.refs)
    }else  if(element === 'plans'){
      node = ReactDom.findDOMNode(this.refs.plans);
    }else  if(element === 'about'){
      node = ReactDom.findDOMNode(this.refs.about);
    }

    node.scrollIntoView({block: 'start', behavior: 'smooth'});

  }

그런 다음 이렇게 참조할 구성 요소를 제공합니다.

<Investments ref="plans"/>

언급URL : https://stackoverflow.com/questions/30495062/how-can-i-scroll-a-div-to-be-visible-in-reactjs