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

Ala*_*nry 5 javascript web-deployment ace-editor reactjs

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

<AceEditor
ref='aceEditor'
height='100%'
width='100%'
mode={ideLanguage}
theme={ideTheme}
fontSize={ideFontSize}
showGutter={true}
showPrintMargin={false}/>
Run Code Online (Sandbox Code Playgroud)

这是按钮

<Button
type='button'
buttonStyle='btn--primary--normal'
buttonSize='btn--medium'
onClick={SendCode}
>SUBMIT</Button>
Run Code Online (Sandbox Code Playgroud)

这就是函数

const SendCode = () => {
  console.log(this.refs.aceEditor.editor.getValue());
};
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么??

Kev*_*yat 18

字符串引用是设置 DOM 引用的传统方法。

在最新的 React 版本中,建议React.useRef()对功能组件和React.createRef()类组件使用钩子。

您可以阅读更多详细信息 - https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs

<React.StrictMode>我可以猜测,您可能已经使用高阶组件打开了严格模式。这就是抛出错误/警告的原因。

你应该做什么——

  1. 声明一个 ref 变量。

    const aceEditorRef = useRef();

  2. 之后,替换ref='aceEditor'ref={aceEditorRef}.

  <AceEditor
    ref={aceEditorRef}
    height='100%'
    width='100%'
    mode={ideLanguage}
    theme={ideTheme}
    fontSize={ideFontSize}
    showGutter={true}
    showPrintMargin={false}/>
Run Code Online (Sandbox Code Playgroud)
  1. 使用 aceEditorRef.current 获取 DOM 引用

    const SendCode = () => {
      console.log(this.aceEditorRef.current.editor.getValue());
    };
    
    
    Run Code Online (Sandbox Code Playgroud)