【问题标题】:How can I scroll to specific section?如何滚动到特定部分?
【发布时间】:2021-12-08 16:24:16
【问题描述】:

我在 React 中使用来自 Facebook 的 Draft JS。

当行以# Section name 开头时,我的draft 在文本上添加装饰器。在我页面上的另一个组件中,我想创建一个链接,当点击时它会向下滚动到该部分。

|-------| ------------|
|Nav    | Draft editor|
|Title 1| # Title 1 |
|.      | Some text |

我的装饰器非常基础:

{
    strategy: (contentBlock: any, callback: any) => {
        const REGEX =/^(# .+)$/
        findWithRegex(REGEX, contentBlock, callback)
    },
    component: (props: any) => {
        
        return <h3>{props.children}</h3>
    }

}

我的导航链接

<a onClick={()=>{
   window.scrollTo() // Scroll to Title 1 in DraftJS
}}>Title 1</a>

在过去的 JS 时代,我会想办法制作一个 ID 并获取元素,但这不是 react 方式。

感谢任何帮助。谢谢。

编辑:这是codesandbox to play around

【问题讨论】:

标签: reactjs draftjs


【解决方案1】:

我不喜欢它,感觉很脏,但如果有人遇到类似的问题,我基本上创建了一个函数,将章节名称转换为 ID,如下所示:

const chapterToId = (txt: string): string => {
    return txt.trim().split("# ").join("").split(" ").join("-").toLowerCase()
}

然后我使用这个函数创建一个# 超链接,如下所示:

{chapters.map((chapter, i) => {
   const chapterId = chapterToId(chapter);
     return <a
          key={i}
          href={`#${chapterId}`}>
               {chapter}
        </a>      
})}

在草稿 JS 中,将 ID 添加到装饰器中,如下所示:

const chapters = {
  strategy: (contentBlock: any, callback: any) => {
    const REGEX = /^(# .+)$/gm;
    findWithRegex(REGEX, contentBlock, callback);
  },
  component: (props: any) => {
    const text = props.children[0].props.text;
    const id = chapterToId(text);
    return (
      <h3 id={id} className="text-2xl font-bold mt-4 mb-6">
        {props.children}
      </h3>
    );
  }
}

这里的工作示例:https://codesandbox.io/s/book-editor-vrfqy?file=/src/components/MyDraft.tsx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    相关资源
    最近更新 更多