[英]ReactJS get ref to child element and setting its scrollTop position
考慮以下呈現的ReactJS組件:
render () {
return (
<div className='ux-table' onScroll={this.handleScroll}>
<table ref='mainTable>
<Header>
**Rows data here***
</table>
</div>
);
還有Header
子組件:
render () {
return (
<thead ref='tableHeader'>
<tr> ** column data here ** </tr>
</thead>
);
}
我需要在主組件句柄上獲取主組件( mainTable
)的scrollTop
位置,並將其設置為子Header組件( tableHeader
),如以下Javascript代碼所示:
document.querySelector('.ux-table').onscroll = function (e) {
// called when the window is scrolled.
var topOfDiv = Math.max(document.querySelector(".ux-table").scrollTop - 2, 0);
document.getElementsByTagName('thead')[0].style = "top:" + topOfDiv + "px;";
}
我嘗試的主要組成部分:
handleScroll = (event) => {
var topOfDiv = Math.max(this.refs.mainTable.scrollTop - 2, 0);
this.refs.tableHeader.scrollTop = topOfDiv;
}
在第一行中,我得到this.refs.mainTable.scrollTop
零(0)。 在第二行中,由於無法直接訪問子組件,因此出現錯誤。
簡而言之,如何:
a)使用ref
讀取並設置React組件的scrollTop
屬性
b)從其父ref
訪問子組件
感謝您的幫助。
我不確定是否有幫助,但是我基於react-markdown制作了一個組件。
它顯示以markdown編寫的幫助頁面,並根據上下文滾動到標題。
渲染組件后,我根據markdown標頭搜索標頭:
import React, { Component } from 'react'; import Markdown from 'react-markdown'; export default class Help extends Component { constructor(props) { super(props); this.state = { md : null } this.helpref = React.createRef(); this.fetchdata() } fetchdata() { fetch("Help-Page.md") .then((r) => r.text()) .then(text => { this.setState({ md:text }); }) } componentDidUpdate(){ // Here i search for the header like : ## My Header let part=this.props.helpHeader.match(/(#+)\\s(.*)/) // If I found it , i search on child for it if(part) for(let childnod of this.helpref.current.childNodes) { // If the child is found if(childnod.nodeName == "H"+part[1].length && childnod.innerText== part[2]) { // I scroll to the element this.helpref.current.scrollTop = childnod.offsetTop } } } render() { return ( <div className="help" ref={this.helpref}> <Markdown source={this.state.md} /> </div> ); } }
照顧
this.helpref = React.createRef();
它需要在渲染后獲取元素,並且不適用於React Component
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.