CSS 如何在 React 中为组件添加滚动条?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50891589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 11:12:41  来源:igfitidea点击:

How to add a scroll bar to a component in React?

cssreactjsscrollbar

提问by Kleo

I'm using a grid system with 3 columns in my SPA. The left and right list contain components that occupy 100 of the viewport height. The middle column contains a long list and would like to add a scrollbar just to the middle component. I've tried to wraw the middle component with several different scrollbar components but nothing works. I end up always with a main page scroll which leaves me only with the list component when scroll further down and left and right component are remaining remain to the top of the page.

我在我的 SPA 中使用了一个有 3 列的网格系统。左右列表包含占据视口高度 100 的组件。中间一列包含一个很长的列表,并想在中间组件中添加一个滚动条。我试图用几个不同的滚动条组件来编写中间组件,但没有任何效果。我最终总是有一个主页滚动,当进一步向下滚动并且左侧和右侧组件保留在页面顶部时,我只剩下列表组件。

回答by inaumov17

Try adding overflow-y: scroll;on the middle component

尝试添加overflow-y: scroll;中间组件

const items = [...Array(100)].map((val, i) => `Item ${i}`);

const App = () => (
  <div className="container">
    <div className="left-col">
      Left col
    </div>
    
    <div className="center-col">
      <span>List</span>
      <ul>
        {items.map((item, i) => (<li key={`item_${i}`}>{ item }</li>))}
      </ul>
    </div>
    
    <div className="right-col">
      Right col
    </div>
  </div>
);

ReactDOM.render(<App />, document.getElementById('react'));
.container {
  display: flex;
  flex-direction: row;
  height: 100vh;
}

.left-col {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #ddd;
}

.center-col {
  flex: 1;
  background: #aaa;
  overflow-y: scroll;
}

.right-col {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #e7e7e7;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="react"></div>

回答by Kleo

Found the solution, need to set fixed height to left and right component and overflow:scroll to middle component.

找到解决办法了,需要给左右组件设置固定高度和overflow:scroll到中间组件。