我有一个聊天小部件,每当我向上滚动时,它就会弹出一个消息数组。我现在面临的问题是,当消息加载时,滑块固定在顶部。我想让它关注上一个数组的最后一个索引元素。我发现我可以通过传递索引来进行动态引用,但我也需要知道使用哪种滚动函数来实现这一点
handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
if (some_logic){
//scroll to testNode
}
}
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
这样,滚动就会转到你要找的任何一行。
干杯,希望它能帮助别人
只需找到您已经确定的元素的顶部位置https://www.w3schools.com/Jsref/prop_element_offsettop.asp,然后通过scrollTo方法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>)
}
更新:
因为React 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>)
}
在阅读manny论坛后,我找到了一个非常简单的解决方案。
我用还原形式。Urgo映射redux-from fieldToClass。当出现错误时,我导航到syncErrors列表中的第一个错误。
没有裁判,没有第三方模块。只是简单的querySelector & scrollIntoView
handleToScroll = (field) => {
const fieldToClass = {
'vehicleIdentifier': 'VehicleIdentifier',
'locationTags': 'LocationTags',
'photos': 'dropzoneContainer',
'description': 'DescriptionInput',
'clientId': 'clientId',
'driverLanguage': 'driverLanguage',
'deliveryName': 'deliveryName',
'deliveryPhone': 'deliveryPhone',
"deliveryEmail": 'deliveryEmail',
"pickupAndReturn": "PickupAndReturn",
"payInCash": "payInCash",
}
document?.querySelector(`.${fieldToClasses[field]}`)
.scrollIntoView({ behavior: "smooth" })
}