You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS(Gatsby)实现点击文章链接在同页面右侧栏展示内容

解决Gatsby博客侧边栏内展示文章内容的问题

核心思路

  • 移除Gatsby自带的Link组件(该组件会触发页面路由跳转),改用自定义点击事件传递文章数据
  • 在父组件IndexPage中维护当前选中文章的状态
  • 根据选中状态在右侧侧边栏渲染对应文章内容

修改步骤及代码

1. 更新PostLink组件

将跳转用的Link替换为普通容器,添加点击回调函数传递文章数据:

import React from "react"

const PostLink = ({ post, onPostClick }) => (
  <div style={{ cursor: "pointer", margin: "8px 0" }} onClick={() => onPostClick(post)}>
    {post.frontmatter.title}
  </div>
)

export default PostLink

2. 修改IndexPage组件

添加状态管理逻辑,处理文章点击事件,并在右侧侧边栏渲染选中的文章内容:

import React, { useState } from "react"

const IndexPage = ({ 
  data: {
    allMarkdownRemark: { edges },
  },
}) => {
  // 初始化选中第一篇文章(若存在)
  const [selectedPost, setSelectedPost] = useState(edges[0]?.node)

  const Posts = edges
    .filter(edge => !!edge.node.frontmatter.date)
    // 给每个PostLink传递点击回调
    .map(edge => <PostLink key={edge.node.id} post={edge.node} onPostClick={setSelectedPost} />)

  return (
    <div className='html-container'>
      <div className='main-container'>
        <div className='row'>
          <div className='left-sidebar'>
            <div className='logo'>
              <p>logo</p>
            </div>
            <div className='menu'>
              {Posts}
            </div>
            <div className='social'>
                <img src={twitch} />
                <img src={discord} />
                <img src={twitter} />
                <img src={email} />
            </div>
          </div>

          <div className='right-sidebar'>
            {/* 渲染选中的文章内容 */}
            {selectedPost && (
              <div className="post-content">
                <h2>{selectedPost.frontmatter.title}</h2>
                <p className="post-date">{selectedPost.frontmatter.date}</p>
                {/* 渲染Markdown解析后的HTML内容 */}
                <div dangerouslySetInnerHTML={{ __html: selectedPost.html }} />
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

关键说明

  • 使用useState钩子跟踪当前选中的文章,初始值设为第一篇文章
  • 点击左侧文章标题时,通过onPostClick回调更新选中状态
  • 右侧侧边栏利用dangerouslySetInnerHTML渲染Gatsby预解析生成的文章HTML内容(请确保文章内容来源可信,避免XSS安全风险)

内容的提问来源于stack exchange,提问作者Adele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 05:10:20