ReactJS 하는 방법으로 스크롤하는 요소

나는 채팅을 위젯을 끌어 당기는 배열의 메시지 마다가 스크롤됩니다. 문제 내가 직면하고 지금은 슬라이더를 조정에 체재하면 상단에 메시지를 로드,나는 그것에 집중하는 마지막 인덱스 요소를 이전에 배열입니다. 제가 생각한 것은 내가 만들 수 있는 동적인 심판을 전달하여 인덱스이지만,또한 것을 알아야 어떤 종류의 스크롤 기능을 달성하기 위해 사용하는

 handleScrollToElement(event) {
    const tesNode = ReactDOM.findDOMNode(this.refs.test)
    if (some_logic){
      //scroll to testNode      
    }
  }

  render() {

    return (
      <div>
        <div ref="test"></div>
      </div>)
  }
질문에 대한 의견 (1)
해결책

반응 16.8 +, 기능성분

const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop)   
// General scroll to element function

const ScrollDemo = () => {

   const myRef = useRef(null)
   const executeScroll = () => scrollToRef(myRef)

   return (

         <div ref={myRef}>I wanna be seen</div> 
          Click to scroll  

   )
}

StackBlits에 대한 전체 데모를 보려면 여기를 클릭하십시오

Response 16.3 +, Class 컴포넌트

class ReadyToScroll extends Component {

    constructor(props) {
        super(props)
        this.myRef = React.createRef()  
    }

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

    scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)   
    // run this method to execute scrolling. 

}

클래스 구성 요소 - 참조 콜백

class ReadyToScroll extends Component {
    myRef=null
    // Optional

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

    scrollToMyRef = () => window.scrollTo(0, this.myRef.offsetTop)
    // run this method to execute scrolling. 
}

문자열 참조는 사용하지 않습니다.

스트링 레프는 성능에 해를 끼치고 컴포지션이 불가능하며 2018년 8월 출시될 예정이다.

문자열 ref는 몇 가지 문제를 가지고 있으며 레거시로서 간주되며 다음을 수행할 가능성이 있다. 는 향후 릴리스 중 하나에서 제거됩니다. [공식 대응 문서]

resource1resource2

선택 사항: 스크롤 애니메이션 평활

/* css */
html {
    scroll-behavior: smooth;
}

자식에게 참조 전달

우리는 ref가 리액트 컴포넌트가 아닌 돔 요소에 부착되기를 원합니다. 그래서 그것을 어린이 구성품에 전달할 때 우리는 소품 레퍼런스 이름을 지정할 수 없습니다.

const MyComponent = () => {
    const myRef = useRef(null)
    return 
}

그런 다음 참조 받침대를 돔 요소에 부착합니다.

const ChildComp = (props) => {
    return <div ref={props.refProp} />
}
해설 (21)

을 찾아 최고의 위치를 요소를've 이미 결정되https://www.w3schools.com/Jsref/prop_element_offsettop.asp스크롤한 다음 이 위치를 통해central방법https://www.w3schools.com/Jsref/met_win_scrollto.asp

다음과 같이 작업:

handleScrollToElement(event) {
  const tesNode = ReactDOM.findDOMNode(this.refs.test)
  if (some_logic){
    window.scrollTo(0, tesNode.offsetTop);
  }
}

render() {

  return (
    <div>
      <div ref="test"></div>
    </div>)
}

업데이트:

이후반응 v16.3반응합니다.createRef()이 선호하는

constructor(props) {
  super(props);
  this.myRef = React.createRef();
}

handleScrollToElement(event) {
  if (){
    window.scrollTo(0, this.myRef.current.offsetTop);
  }
}

render() {

  return (
    <div>
      <div ref={this.myRef}></div>
    </div>)
}
해설 (5)

이 나를 위해 일

this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
해설 (3)

사용 findDOMNode 될 것입니다 결국에는 사용되지 않.

선호하는 방법은 콜백을 사용하 refs.

github eslint

해설 (1)

또한 사용할 수 있습니다scrollIntoView방법을 스크롤해 지정된 요소입니다.

handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
 if (some_logic){
  tesNode.scrollIntoView();
  }
 }

 render() {
  return (
   <div>
     <div ref="test"></div>
   </div>)
}
해설 (0)

내가 될 수 있는 자이지만 나를 구현하기 위해 노력하고 동적인 심판을 내 프로젝트에 적절한 방법으로 모든 대답을 찾았을 때까지 알지't 한 만족스러운 내가 좋아하는 것,그래서 저는 솔루션으로 생각하는 간단하고 사용하는 기본 및 권장 방법으로의 반응을 만들 ref.

때때로 당신은 당신을 찾는 방법은 설명서를 작성하는 것으로 가져 있 금액의 전망과 대부분의 경우 이 번호를 알 수없는,그래서 당신이 필요가 문제를 해결하는 방법에 이 경우,역사 심판을의 알 수없는 전망을 보여줄 필요가에서 클래스

그래서 가장 간단한 해결책이 나는 생각할 수 있고 완벽하게 작동하도록 다음과 같이

class YourClass extends component {

state={
 foo:"bar",
 dynamicViews:[],
 myData:[] //get some data from the web
}

inputRef = React.createRef()

componentDidMount(){
  this.createViews()
}

createViews = ()=>{
const trs=[]
for (let i = 1; i < this.state.myData.lenght; i++) {

let ref =`myrefRow ${i}`

this[ref]= React.createRef()

  const row = (
  <tr ref={this[ref]}>
<td>
  `myRow ${i}`
</td>
</tr>
)
trs.push(row)

}
this.setState({dynamicViews:trs})
}

clickHandler = ()=>{

//const scrollToView = this.inputRef.current.value
//That to select the value of the inputbox bt for demostrate the //example

value=`myrefRow ${30}`

  this[value].current.scrollIntoView({ behavior: "smooth", block: "start" });
}

render(){

return(
<div style={{display:"flex", flexDirection:"column"}}>
 Search
<input ref={this.inputRef}/>
<table>
<tbody>
{this.state.dynamicViews}
<tbody>
<table>
</div>

)

}

}

export default YourClass

는 방법으로 스크롤을 갈 것입니다 무엇을 행한다면...

환호와 희망 그것은 다른 사람들

해설 (0)

당신이 이것을 시도해 볼 수도 있습니는 길:

 handleScrollToElement = e => {
    const elementTop = this.gate.offsetTop;
    window.scrollTo(0, elementTop);
 };

 render(){
  return(
      <h2 ref={elem => (this.gate = elem)}>Payment gate</h2>
 )}
해설 (1)

당신은 지금 사용할 수 있습니다useRef에서 반응하는 훅 API

https://reactjs.org/docs/hooks-reference.html#useref

선언

자 myRef=useRef()

구성 요소

``

나의 구성요소
``

사용

창입니다.central({행동:&#39;드&#39;,최고:myRef.현재 있습니다.offsetTop})

해설 (1)

같은 것을 사용할 수 있습니다은 첫째

componentDidUpdate() {
  var elem = testNode //your ref to the element say testNode in your case; 
  elem.scrollTop = elem.scrollHeight;
};
해설 (3)

Jul2019-전용 훅/기능

전용 훅/기능을 수 있는지 구체,제공하고 간단한 API 를 구성 요소입니다.

반응 16.8+능성

``js const useScroll=()=>{ const htmlElRef=useRef(null) const executeScroll=()=>window.central(0,htmlElRef.현재 있습니다.offsetTop)

return[executeScroll,htmlElRef] } 에서 사용하는 어떤 기능의 구성 요소입니다. const ScrollDemo=()=>{ const[executeScroll,htmlElRef]=useScroll() useEffect(executeScroll,[])//후 실행되는 구성 요소를 탑재

return

쇼 나
} `` 전 demo

반응 16.3+클래스 구성 요소

``js const utilizeScroll=()=>{ const htmlElRef=React.createRef() const executeScroll=()=>window.central(0,htmlElRef.현재 있습니다.offsetTop)

return{executeScroll,htmlElRef} } 에서 사용하는 모든 클래스 구성 요소입니다. js 클래스 ScrollDemo 확장 구성 요소{ 생성자를(){ 다.elScroll=utilizeScroll() }

componentDidMount(){ 다.elScroll.executeScroll() }

render(){ return

쇼 나
} } `` 전 demo

해설 (0)

어떤 나를 위해 일했:

class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef(); // Create a ref    
    }

    // Scroll to ref function
    scrollToMyRef = () => {
        window.scrollTo({
            top:this.myRef.offsetTop, 
            // behavior: "smooth" // optional
        });
    };

    // On component mount, scroll to ref
    componentDidMount() {
        this.scrollToMyRef();
    }

    // Render method. Note, that `div` element got `ref`.
    render() {
        return (
            <div ref={this.myRef}>My component</div>
        )
    }
}
해설 (0)
 <div onScrollCapture={() => this._onScrollEvent()}></div>

 _onScrollEvent = (e)=>{
     const top = e.nativeEvent.target.scrollTop;
     console.log(top); 
}
해설 (0)