ReactJS 获取子元素的引用并设置其 scrollTop 位置



考虑以下渲染的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位置,并将其设置为子标头组件(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 组件

最新更新