스크롤 할 때마다 여러 메시지를 표시하는 채팅 위젯이 있습니다. 내가 지금 직면하고있는 문제는 메시지가로드 될 때 슬라이더가 맨 위에 고정되어 있다는 것입니다. 이전 배열의 마지막 색인 요소에 초점을 맞추고 싶습니다. 인덱스를 전달하여 동적 참조를 만들 수 있다는 것을 알았지 만이를 달성하기 위해 사용할 스크롤 기능의 종류도 알아야합니다.
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
//scroll to testNode
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
답변
반응식 16.8 +, 기능 컴포넌트
import React, { useRef } from 'react'
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>
<button onClick={executeScroll}> Click to scroll </button>
</>
)
}
StackBlits에 대한 전체 데모를 보려면 여기를 클릭하십시오.
반응 16.3 +, 클래스 구성 요소
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.
}
클래스 컴포넌트-Ref 콜백
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 월).
문자열 참조에는 몇 가지 문제가 있으며 레거시로 간주되며 향후 릴리스 중 하나에서 제거 될 수 있습니다. [공식 리 액트 문서]
선택 사항 : 스크롤 애니메이션 다듬기
/* css */
html {
scroll-behavior: smooth;
}
아이에게 심판을 전달
우리는 ref가 반응 요소가 아닌 dom 요소에 부착되기를 원합니다. 따라서 하위 컴포넌트로 전달할 때 prop ref의 이름을 지정할 수 없습니다.
const MyComponent = () => {
const myRef = useRef(null)
return <ChildComp refProp={myRef}></ChildComp>
}
그런 다음 심판 소품을 돔 요소에 부착하십시오.
const ChildComp = (props) => {
return <div ref={props.refProp} />
}
답변
이것은 나를 위해 일했다
this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
편집 : 나는 의견에 따라 이것을 확장하고 싶었습니다.
const scrollTo = (ref) => {
if (ref /* + other conditions */) {
ref.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
}
<div ref={scrollTo}>Item</div>
답변
https://www.w3schools.com/Jsref/prop_element_offsettop.asp에서 이미 결정한 요소의 상단 위치를 찾은 다음 https://www.w3schools.com/Jsref/met_win_scrollto.aspscrollTo
메소드 를 통해이 위치로 스크롤 하십시오.
이와 같은 것이 작동해야합니다.
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 반작용React.createRef()
바람직
constructor(props) {
super(props);
this.myRef = React.createRef();
}
handleScrollToElement(event) {
if (<some_logic>){
window.scrollTo(0, this.myRef.current.offsetTop);
}
}
render() {
return (
<div>
<div ref={this.myRef}></div>
</div>)
}
답변
답변
이제 useRef
반응 후크 API에서 사용할 수 있습니다
https://reactjs.org/docs/hooks-reference.html#useref
선언
let myRef = useRef()
구성 요소
<div ref={myRef}>My Component</div>
사용하다
window.scrollTo({ behavior: 'smooth', top: myRef.current.offsetTop })
답변
scrollIntoView
메소드를 사용 하여 주어진 요소로 스크롤 할 수도 있습니다 .
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
tesNode.scrollIntoView();
}
}
render() {
return (
<div>
<div ref="test"></div>
</div>)
}
답변
파티에 늦었을 수도 있지만 적절한 방법으로 내 프로젝트에 동적 참조를 구현하려고했지만 알 때까지 찾은 모든 대답은 내 취향에 만족하지 못하므로 내가 생각하는 해결책을 생각해 냈습니다. 단순하고 기본적이고 권장되는 반응 방식을 사용하여 심판을 만듭니다.
때로는 문서 작성 방법이 알려진 양의 뷰가 있다고 가정하고 대부분의 경우이 수를 알 수 없으므로이 경우 문제를 해결하는 방법이 필요하며 필요한 수의 알 수없는 뷰에 대한 동적 참조를 작성하십시오 수업에 보여
그래서 내가 생각하고 완벽하게 작동 할 수있는 가장 간단한 해결책은 다음과 같습니다.
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"}}>
<Button onClick={this.clickHandler}> Search</Button>
<input ref={this.inputRef}/>
<table>
<tbody>
{this.state.dynamicViews}
<tbody>
<table>
</div>
)
}
}
export default YourClass
이렇게하면 스크롤이 원하는 행으로 이동합니다 ..
환호하고 그것이 다른 사람들을 돕는 희망
