【问题标题】:Error: Function components cannot have string refs. We recommend using useRef() instead错误:函数组件不能有字符串引用。我们建议改用 useRef()
【发布时间】:2020-08-07 04:57:44
【问题描述】:

我在我的 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());
};

我做错了什么??

【问题讨论】:

  • 您介意分享定义 ref/sendCode 函数并呈现按钮的代码吗?一个 sn-p 代码将是理想的

标签: javascript reactjs web-deployment ace-editor


【解决方案1】:

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

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

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

我可以猜到,您可能已经使用&lt;React.StrictMode&gt; 高阶组件打开了严格模式。这就是为什么会抛出错误/警告。

你应该怎么做-

  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}/>
  1. 使用 aceEditorRef.current 获取 DOM 引用

    const SendCode = () => {
      console.log(this.aceEditorRef.current.editor.getValue());
    };
    
    

【讨论】:

  • 我对 React 比较陌生。您能否以简单的方式解释我可以对代码进行哪些更改以达到预期的结果。提前致谢
  • 声明一个 ref 变量。 const aceEditorRef = useRef(); 之后,将 ref='aceEditor' 替换为 ref={aceEditorRef} 。使用 aceEditorRef.current 获取 DOM 引用。
猜你喜欢
  • 1970-01-01
  • 2021-01-05
  • 2014-10-30
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多