错误:函数组件不能有字符串引用。我们建议改用 useRef()

我在我的 React 应用程序中使用 ace Editor 并收到上述错误。我想将我在我的 React 应用程序中使用的 Ace Editor IDE 的内容放在通过提交按钮触发的函数调用中。


<AceEditor

ref='aceEditor'

height='100%'

width='100%'

mode={ideLanguage}

theme={ideTheme}

fontSize={ideFontSize}

showGutter={true}

showPrintMargin={false}/>

这是按钮


<Button

type='button'

buttonStyle='btn--primary--normal'

buttonSize='btn--medium'

onClick={SendCode}

>SUBMIT</Button>

这是功能


const SendCode = () => {

  console.log(this.refs.aceEditor.editor.getValue());

};

我究竟做错了什么??


慕田峪4524236
浏览 104回答 1
1回答

肥皂起泡泡

字符串引用是设置 DOM 引用的传统方式。在最新的 React 版本中,建议对功能组件和类组件使用React.useRef()钩子。React.createRef()您可以阅读更多详细信息 -&nbsp;https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs我猜,你可能已经打开了<React.StrictMode>高阶组件的严格模式。这就是为什么会抛出错误/警告的原因。你应该做什么 -声明一个 ref 变量。const aceEditorRef = useRef();之后,替换ref='aceEditor'为ref={aceEditorRef}。&nbsp;<AceEditor&nbsp; &nbsp; ref={aceEditorRef}&nbsp; &nbsp; height='100%'&nbsp; &nbsp; width='100%'&nbsp; &nbsp; mode={ideLanguage}&nbsp; &nbsp; theme={ideTheme}&nbsp; &nbsp; fontSize={ideFontSize}&nbsp; &nbsp; showGutter={true}&nbsp; &nbsp; showPrintMargin={false}/>使用 aceEditorRef.current 获取 DOM 引用const SendCode = () => {&nbsp; console.log(this.aceEditorRef.current.editor.getValue());};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript