【问题标题】:How to use variable inside useEffect in Reactjs如何在 Reactjs 的 useEffect 中使用变量
【发布时间】:2022-12-19 17:59:34
【问题描述】:

我正在使用 Reactjs,我正在使用 Nextjs,现在我正在尝试获取“编辑器”的值,我想知道 如何在“handleSubmit 函数”中获取“变量值”?换句话说,我如何提醒 handleSubmit 按钮内的编辑器值? 这是我当前的代码,提前谢谢你。

const [editor, setEditor] = useState()
    
useEffect(() => {
 if(editor){
   const content = editor.getContent();
   console.log('content is ' + content); //How can i pass "content to handlesubmit"
 }
}, [editor])
    
const handleSubmit = async(e: any) => {
  e.preventDefault();
  alert('content is ' + content);
}

// ...

     <Editor
        onInit={(evt, ed) => {
            setEditor(ed);
           }}
        initialValue="<p>This is the initial content of the editor.</p>"
        init={{
          height: 500,
          menubar: false,
          plugins: [
            'advlist autolink lists link image charmap print preview anchor',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table paste code help wordcount'
          ],
          toolbar: 'undo redo | formatselect | ' +
          'bold italic backcolor | alignleft aligncenter ' +
          'alignright alignjustify | bullist numlist outdent indent | ' +
          'removeformat | help',
          content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
        }}
  />

【问题讨论】:

  • handleSubmit本身包含Editor,你要把内容传到哪里? @Phil 建议了获取内容的方式。
  • 我认为需要更多相关代码才能给出更好的答案,但是如果编辑器初始化一次然后使用 useRef 并引用 handleSubmit 中的当前值在您的情况下不起作用

标签: reactjs typescript next.js


【解决方案1】:

只需在 handleSubmit 函数中引用 editor 即可。

如果在调用handleSubmit()时未设置editor,它将是undefined,否则它将能够返回getContent()的值。

如果您需要在那时有条件地做某事,只需检查该值

const handleSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
  const content = editor?.getContent();
  alert(`content is ${content}`);
  if (content) {
    // ...
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2020-12-01
    • 2021-12-20
    • 2020-06-14
    • 2021-11-22
    • 1970-01-01
    • 2017-06-24
    • 2020-09-18
    相关资源
    最近更新 更多