【问题标题】:Using react-sticky to make a sticky header使用 react-sticky 制作粘性标题
【发布时间】:2019-03-16 15:36:22
【问题描述】:

我正在尝试使用 react-sticky 包制作粘性标题,但我的标题一直滚动到视野之外。这是包裹:https://www.npmjs.com/package/react-sticky 我不确定我是否正确使用了 StickyContainer 或 Sticky 组件。我实际上对您应该传递给 Sticky 容器的“样式”道具有点困惑。

如果有人可以提供帮助,将不胜感激。谢谢!

这是 App.js 的代码:

import React, { Component } from 'react';
import './App.css';
import Header from './components/Header';
import Footer from './components/Footer';
import HomePage from './components/pages/HomePage';
import OurWork from './components/pages/OurWork';
import ContactUs from './components/pages/ContactUs';
import { BreakpointProvider } from 'react-socks';
import { StickyContainer, Sticky } from "react-sticky";
import { setDefaultBreakpoints } from 'react-socks';

setDefaultBreakpoints([
  { small: 0 },
  { medium: 700 }
]);

class App extends Component {
  pageStyle = {
    display: 'flex',
    flexDirection: 'column'
  }

  render() {
    return (
      <BreakpointProvider>
        <StickyContainer>
          <div className="App">
            <Sticky>
              {({style}) => <Header style={style}/>}
            </Sticky>
            <div className="page" style={this.pageStyle}>
                <HomePage />
              <OurWork />
              <ContactUs />
            </div>
          <Footer />
        </div>
        </StickyContainer>
      </BreakpointProvider>
    );
  }
}

export default App;

这里是 Header 组件:

import React, { Component } from 'react';
import Logo from './Logo'
import NavBar from './NavBar';
import logo from '../images/transparent.png';

class Header extends Component {
    headerStyle = {
        height: 100,
        margin: 20,
        display: 'flex',
        justifyContent: 'space-between',
        zIndex: 10
    };

    render() {
        return (
            <div className="header" style={this.headerStyle}>
                <Logo logo={logo}/>
                <NavBar />
            </div>
        );
    }

};

export default Header;

【问题讨论】:

  • 如果您的目标是始终将标题放在同一个位置,您应该使用 position: fixed。 Sticky 可以使元素停留在一个位置,直到给定的滚动位置。
  • @Fantastisk 是的,这解决了我的问题。非常感谢!
  • 太棒了!欢迎你:)
  • 对于其他可能想要将 react-sticky 用于不同目的的人,我也发现它非常棘手并且无法使其工作。不过,您可能需要检查此代码框:codesandbox.io/s/z715b?file=/src/components/content/… check components->content->ListToolSelectButton.jsx

标签: javascript css reactjs react-sticky


【解决方案1】:

sticky header不需要外部库,查看此资源React Table Sticky Header without external library

演示

诀窍是这样的

1 .划分表头和数据部分

  1. 两者都使用固定宽度

  2. 用 div 包裹数据容器,给容器 div 一个固定的高度, 允许

    .container { overflox-y:滚动; 高度:300px; }

【讨论】:

    猜你喜欢
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多