我有一个作为父组件的LiteratureList组件和一个文学组件(子组件)。根据数据库中存储了多少文献条目,文献组件会从父级调用几次。因此,例如,在数据库中有5个文献条目,将呈现5个不同的文献组件。
在第一次呈现之后,第一个“文献”对象有一个状态变量active:true。每个其他的“文献”对象都有一个状态变量active:false。我通过用不同的颜色高亮显示活动对象。现在,当我按enter键时,第二个文献对象被设置为活动的。
现在我遇到了这样的问题:如果我按enter键3次,活动对象就会跳出我的浏览器视图,因为我没有window.scrollTo函数,所以它会自动滚动到我的活动对象。
这基本上就是我的父级代码:
class LiteratureList extends Component {
constructor(props) {
super(props);
this.state = {
highlightIndex: 0,
literatureEntries: ...get from database,
}}
....
handleEnterPress(e){
const keyCode = e.keyCode
if (keyCode === 13) { //enter key -> increase index of the
//item which should be
//highlighted by one -> next card will
//be highlighted
this.setState({ highlightIndex: this.state.highlightIndex + 1 })
}
}
render()
return(
{
this.state.literatureEntries.map((literature, index) => {
let active = true;
if (this.state.highlightIndex !== index) {
active = false
}
return (
<Literature literature={literature}
active={active}/>)
})
}
)
}这是我的孩子(文学)组件:
export default class Literature extends Component {
constructor(props) {
super(props);
this.state = {
active: props.active,
literature: props.literature,
}
}
...
render()
return(
<Col xs="12" key={literature._id}>
<Card id={this.state.active ? "highlight" : null} className={this.state.active ? "highlight" : null}>
....some text ...
</Card>
</Col>
)
}我已经尝试在父对象中设置每个scrollIntoView对象的ref,然后像这样调用scrollIntoView:
class LiteratureList extends Component{
...
handleEnterPress(e){
...
this.active.current.scrollIntoView({ behavior: 'smooth', block: 'start' }) //active because I set
//the ref = "active" if
//Literature object is active
}
...
render()
return(
... <Literature ref={() => { if (active) { return "active" } else { return "inactive" } }}
literature={literature} active={active}/>)
)
}但是使用这段代码,我会得到错误TypeError: Cannot read property 'current' of undefined
发布于 2020-05-12 03:44:50
您的代码令人困惑,因此我将尝试解释您在不使用您的代码的情况下需要做什么。
您需要一些状态和一个属性。
state = {
currentIndex: 0, // index of the active item
literatures: [] // the list of literatures
}
literaturesRef = [] // array of references of the Literature component因此,您将需要呈现文献列表,并使用索引设置该组件的引用。
this.state.literatures.map((literature, i) => (
<Literature
ref={ref => literaturesRef[i] = ref} // correct way of setting the ref
literature={literature}
active={this.state.currentIndex === i}
/>
))现在,当您在handleEnterPress中按enter键时,您将使用currentIndex访问literaturesRef并调用scrollIntoView
handleEnterPress = e => {
// correctly accessing the reference of the current index
this.literaturesRef[currentIndex].current.scrollIntoView({ behavior: 'smooth', block: 'start' })
}编辑
我忘了一个细节。您将ref传递给Literature,但在其内部,您需要将该ref传递给doom元素(可能是div),因此,当您访问this.literaturesRef[this.state.currentIndex]时,它是一个doom元素,它将具有方法scrollIntoView,并且您不会得到注释中描述的错误
https://stackoverflow.com/questions/61733053
复制相似问题