React项目中无法获取EditorContainer的codeRef.current问题求助
React组件间获取编辑器内容的问题解决
问题描述
在React项目中,需要在PlaygroundScreen(对应index.js)中获取EditorContainer组件内的编辑器内容,用于调用saveCode方法,但当前index.js报错**'codeRef' is not defined**。尝试通过组件传参传递codeRef时,又出现无法读取.current的错误。
报错信息
src\Screens\PlaygroundScreen\index.js
Line 20:30: 'codeRef' is not defined
问题根源
codeRef是EditorContainer内部的局部变量,父组件PlaygroundScreen无法直接访问子组件的内部ref。- 子组件参数接收方式错误,且未正确使用React的ref传递机制。
解决方案
步骤说明
- 在父组件
PlaygroundScreen中创建ref实例,通过props传递给子组件EditorContainer。 - 子组件接收父组件传递的ref,在编辑器内容变化时更新该ref的
current值。 - 父组件直接使用自身创建的ref获取编辑器内容。
修改后的代码
index.js
import { useNavigate, useParams } from "react-router-dom"; import "./playground.scss"; import codelogo from "./vlogo.png"; import { PlaygroundContext } from "../../Providers/PlaygroundProvider"; import { EditorContainer } from "./EditorContainer"; import { useContext, useRef } from "react"; export const PlaygroundScreen = () =>{ const {saveCode} = useContext(PlaygroundContext); const navigate = useNavigate(); // 修正变量名,避免与组件重名 const codeRef = useRef(''); // 父组件初始化ref const homepage = () => { navigate(`/`); } const onSaveCode = () => { saveCode(fileId, id, codeRef.current); alert("Code Saved"); } const params = useParams(); const {fileId, id} = params; return( <div className="main-container"> <div className="title-container"> <div className="brand-container"> <img src={codelogo} alt="代码logo"></img> </div> <div className="button-container"> <span className="material-symbols-outlined" onClick={onSaveCode}>save</span> <span className="material-symbols-outlined" onClick={homepage}>arrow_back</span> <div className="purple-stuff"></div> </div> </div> <div className="code-container"> <EditorContainer codeRef={codeRef} /> {/* 传递ref给子组件 */} </div> </div> ); }
EditorContainer.js
import { useState } from "react"; import "./EditorContainer.scss" import Editor from "@monaco-editor/react"; import { PlaygroundContext } from "../../Providers/PlaygroundProvider"; // 正确接收props对象,解构出codeRef export const EditorContainer = ({ codeRef }) =>{ const [code, setCode] = useState(''); const editorOptions={ theme: 'vs-dark', wordWrap: 'on' } const onChangeCode = (newCode) =>{ console.log(newCode); // setCode(newCode); codeRef.current = newCode; // 更新父组件ref的current值 } return( <div className="root-editor-container"> <Editor height={"100%"} language={"javascript"} options={editorOptions} theme={'vs-dark'} onChange={onChangeCode} /> </div> ) }
额外修正点
- 原代码中
const Navigate = useNavigate();变量名与React Router的Navigate组件重名,改为小写navigate避免冲突。 - 子组件原参数接收方式
(fileId, id)错误,React组件参数为props对象,需改为解构形式({ codeRef })。 - 移除子组件内部的
codeRef定义,直接复用父组件传递的ref。
内容的提问来源于stack exchange,提问作者Divyansh Pathak
相关产品推荐
相关产品推荐

