【发布时间】:2018-12-26 11:15:11
【问题描述】:
我有一个包含一系列项目的列表,但我无法让它滚动另一个项目进入视图。 this 之类的解决方案不太管用,因为我必须上下滚动(基本上如果列表太大,请间隔滚动以显示所有项目)。
我做了一个codepen 来说明 react-scroll-to-component 的问题,但我对任何库/本机解决方案持开放态度。基本功能只是scrollToComponent(ref, <options>)。
据我所知,错误是它试图在正文上滚动,而不是在实际容器上滚动。如果你删除了 div 的高度/溢出属性,它会起作用。
不起作用:
<div
style={{
height: `200px`,
overflow: "hidden"
}}
>
{this.state.items.map(item => (
<Item ref={inst => (this[`ref_${item}`] = inst)} item={item} />
))}
</div>
作品:
<div>
{this.state.items.map(item => (
<Item ref={inst => (this[`ref_${item}`] = inst)} item={item} />
))}
</div>
任何不想去 codepen 的人的完整代码:
class Item extends React.Component {
render() {
return <div style={{ padding: `12px` }}>Item {this.props.item}</div>;
}
}
class List extends React.Component {
state = {
items: [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
]
};
componendDidMount() {
this.state.items.forEach(item => (this[`ref_${item}`] = React.createRef()));
}
onClick = () => {
scrollToComponent(this.ref_20);
};
render() {
const { items } = this.state;
return (
<div>
<h1>My List</h1>
<button onClick={this.onClick}>Clickidy</button>
{/*Replace with <div> to see it work*/}
<div
style={{
height: `200px`,
overflow: "hidden",
backgroundColor: "red"
}}
>
{this.state.items.map(item => (
<Item ref={inst => (this[`ref_${item}`] = inst)} item={item} />
))}
</div>
</div>
);
}
}
【问题讨论】:
-
github.com/fisshy/react-scroll - 允许设置容器
标签: javascript reactjs scroll