React中如何实现点击文章预览后用Article组件替换页面content内容区域
解决React博客预览转文章详情的实现方案
嘿,我来帮你搞定这个问题~首先得说,你原来的思路里有几个不符合React数据流的地方,直接操作DOM替换不是React推荐的方式,咱们用状态驱动视图的方式来实现会更优雅,而且也符合React的设计理念。
先给你指出原代码里的几个小问题:
- 函数定义语法错误:
redirectToArticle(id) = () => {}这种写法不对,函数组件里应该用const redirectToArticle = (id) => {} - onClick事件直接调用函数会导致组件渲染时立即执行,应该用箭头函数包裹,比如
onClick={() => redirectToArticle(1)} - Article组件里错误地访问
this.title,应该是this.props.title(因为title是通过props传进来的)
接下来是完整的正确实现:
方案一:函数组件 + useState(推荐)
import { useState } from 'react'; // 先修正Article组件,正确接收props const Article = ({ title, content }) => { return ( <> <h1>{title}</h1> <p>{content}</p> </> ); }; function Blog() { // 用state管理当前选中的文章ID,初始为null表示显示预览列表 const [selectedArticleId, setSelectedArticleId] = useState(null); // 模拟获取文章标题和内容的函数 const getTitle = (id) => { return `Article Title ${id}`; }; const getContent = (id) => { return `Full content of article ${id}... Lorem ipsum dolor sit amet, consectetur adipiscing elit.`; }; // 点击预览时设置选中的文章ID const redirectToArticle = (id) => { setSelectedArticleId(id); }; // 根据state决定渲染内容 if (selectedArticleId) { const title = getTitle(selectedArticleId); const content = getContent(selectedArticleId); return ( <div className="content"> <Article title={title} content={content} /> </div> ); } // 没有选中文章时显示预览列表 return ( <div className="content"> <div onClick={() => redirectToArticle(1)} style={{ cursor: 'pointer' }}> <h1>Article Title 1</h1> <p>Short preview from the article here...</p> </div> {/* 可以添加更多文章预览 */} <div onClick={() => redirectToArticle(2)} style={{ cursor: 'pointer', marginTop: '20px' }}> <h1>Article Title 2</h1> <p>Another short preview...</p> </div> </div> ); }
方案二:类组件实现(如果你习惯用类组件)
import React, { Component } from 'react'; class Article extends Component { render() { // 修正为从props获取数据 const { title, content } = this.props; return ( <> <h1>{title}</h1> <p>{content}</p> </> ); } } class Blog extends Component { constructor(props) { super(props); this.state = { selectedArticleId: null }; } getTitle = (id) => { return `Article Title ${id}`; }; getContent = (id) => { return `Full content of article ${id}... Lorem ipsum dolor sit amet, consectetur adipiscing elit.`; }; redirectToArticle = (id) => { this.setState({ selectedArticleId: id }); }; render() { const { selectedArticleId } = this.state; if (selectedArticleId) { const title = this.getTitle(selectedArticleId); const content = this.getContent(selectedArticleId); return ( <div className="content"> <Article title={title} content={content} /> </div> ); } return ( <div className="content"> <div onClick={() => this.redirectToArticle(1)} style={{ cursor: 'pointer' }}> <h1>Article Title 1</h1> <p>Short preview from the article here...</p> </div> </div> ); } }
核心思路说明:
- 用状态控制视图:通过
selectedArticleId这个状态变量,判断当前应该显示预览列表还是文章详情 - 避免直接操作DOM:React的核心是数据驱动视图,状态变化后会自动重新渲染对应的组件,不需要手动去替换DOM元素
- 修正事件绑定:onClick事件需要用箭头函数包裹,确保只有点击时才会执行
redirectToArticle函数
内容的提问来源于stack exchange,提问作者Can Efe
相关产品推荐
相关产品推荐

