如何在 React 中为 React-Perfect-Scrollbar 添加选项

How to add options to react-perfect-scrollbar in react

我正在使用 react-perfect-scrollbar 并像这样初始化

<PerfectScrollbar
    onScrollY={container => console.log(`scrolled to: ${container.scrollTop}.`)}>
    ... SCROLLBAR CONTENT HERE ...
</PerfectScrollbar>

我正在尝试添加 options,特别是 suppressScrollY。我试过了

<PerfectScrollbar
    options={{ suppressScrollY: true }}
    ... SCROLLBAR CONTENT HERE ...
</PerfectScrollbar>

它被忽略了。

我在这里错过了什么? 谢谢

我会升级到撰写本文时的最新版本 1.5.6。原因之一是,如果您查看他们的文档,他们以前将此道具命名为 option 而不是 options。我已经在 CodeSandBox 中测试了这个理论,我可以得出结论,属于 suppressScrollYoptions 道具仅适用于 1.5.1 及以上。

我发现的另一个问题是他们的组件目前与 re-rendering 有问题。例如,如果您最初将 suppressScrollY 设置为 true 并将其状态设置为 false,则更改不会立即反映出来。不幸的是,为了解决这个问题,您必须 re-mount 组件。

在下面的代码中查看我的评论:

import React, { useState } from "react";
import "react-perfect-scrollbar/dist/css/styles.css";
import PerfectScrollbar from "react-perfect-scrollbar";

export default function App() {
  // holds the state if scrollY should be suppressed
  const [scrollYSuppressed, setScrollYSuppressed] = useState(true);

  // holds the state for the key prop of PerfectScrollbar
  // will be incremented to force re-mounting of component
  // due to issues with reinitializing options prop
  const [key, setKey] = useState(0);

  const sampleContainer = {
    maxHeight: "100px"
  };

  const sampleContent = {
    height: "200px",
    background: "black"
  };

  return (
    <div className="App">
      <PerfectScrollbar
        style={sampleContainer}
        options={{ suppressScrollY: scrollYSuppressed }}
        onScrollY={(container) =>
          console.log(`scrolled to: ${container.scrollTop}.`)
        }
        key={key}
      >
        <div style={sampleContent}></div>
      </PerfectScrollbar>
      <div>scrollYSuppressed: {scrollYSuppressed.toString()}</div>
      <button
        onClick={() => {
          setScrollYSuppressed(!scrollYSuppressed);
          setKey(key + 1);
        }}
      >
        Toggle Scroll Y
      </button>
    </div>
  );
}