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

React中如何将类组件的state传递给同一页面的函数组件

实现方案

场景1:Input和Display在同一页面内相邻渲染

直接采用状态提升方案即可实现状态同步:

  • 将fileContent、fileName两个共享状态提到两个组件的公共父组件中定义
  • 给Input组件传递更新状态的回调方法,Input处理完文件内容后调用该回调更新父组件状态
  • 父组件直接把fileContent作为props传递给Display组件即可

公共父组件示例代码

import { Component } from 'react';
import Input from './Input';
import Display from './Display';

class Parent extends Component {
  constructor(props){
    super(props);
    this.state = {
      fileName: '',
      fileContent: ''
    };
  }
  // 传递给Input组件的更新回调
  updateFile = (fileName, fileContent) => {
    this.setState({ fileName, fileContent });
  }
  render(){
    return (
      <>
        <Input updateFile={this.updateFile} />
        <Display fileContent={this.state.fileContent} />
      </>
    )
  }
}

修改后的Input组件核心代码

你需要删除Input组件自身定义的fileName、fileContent状态,所有状态更新都调用父组件传递的updateFile方法:

// Input组件内reader.onload逻辑修改示例
reader.onload = () => {
  let content = reader.result;
  if(content.includes('//')){
    // 你原有处理content的逻辑不变
    let prevPart = null;
    const newText1 = content.split('\n').filter(x => !x.includes('//')).join('\n')
    const newText2 = newText1.split('/').map(part => {
      if (part.startsWith('*') && part.endsWith('*')) {
        prevPart = null;
        return null;
      }
      if (prevPart !== null) part = '/' + part;
      prevPart = part;
      return part;
    }).filter(part => part !== null).join('');
    content = newText2
  }
  // 调用父组件方法更新状态
  this.props.updateFile(file.name, content);
}

场景2:Display在/output路由下(你代码中用到了跳转)

直接用React Router的路由state参数传递即可:

修改Input组件中的Link代码

<Link 
  to={{
    pathname: '/output',
    state: {
      fileContent: this.state.fileContent,
      fileName: this.state.fileName
    }
  }}
>
  Show File
</Link>

修改后的Display组件代码

import { useLocation } from 'react-router-dom';

const Display = () =>{
  const location = useLocation();
  // 读取路由传递的参数,容错处理避免跳转时无参数报错
  const fileContent = location.state?.fileContent || '未读取到文件内容';
  return(
    <>
      <h2>Display File</h2>
      <p>{fileContent}</p>
    </>
  );
};

如果需要跨多个组件、多个路由共享状态,可以使用React Context或轻量状态管理库实现全局状态同步,避免逐层传递props。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:36:03