React表单组件没有使用Tiny MCE更新



import { useState } from 'react';
import { Editor } from "@tinymce/tinymce-react";
import "./NewBlogPost.css";
function NewBlogPost(props) {
const [formData, setFormData] = useState({
title: '',
content: '',
image_url: ''
})
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prevState => ({
...prevState,
[name]: value
}))
}
const saveBlog = (e) => {
e.preventDefault();
props.handleCreate({
...formData
})
}
const clearForm = (e) => {
e.preventDefault();
setFormData({
title: '',
content: '',
image_url: ''
})
}
return (
<div>
<h1>Create New Blog Post</h1>
<form
className="new-blog-form"
onSubmit={saveBlog}>
<div>
<label className="form-label">Title:
<input
className="form-input"
type='text'
name='title'
value={formData.title}
onChange={handleChange}
/>
</label>
</div>
<div>
<label className="form-label">Image URL:
<input
className="form-input"
type='text'
name='image_url'
value={formData.image_url}
onChange={handleChange}
/>
</label>
</div>
<div>
<label> Content:
<Editor
textareaName="text-area"
name='content'
value={formData.content}
outputFormat= 'text'
init={{
height: 500,
width: 420,
menubar: false,
toolbar: 'undo redo | formatselect | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | help'
}}
onChange={handleChange}
/>
</label>
</div>
<div>
<button className="button" id="save-button">Save</button>
<button
className="button"
id="clear-button"
onClick={clearForm}
>Clear</button>
</div>
</form>
</div>
);
}
export default NewBlogPost; 

你需要做一些改变,以适应时间编辑器在你的代码,仍然保持你的handleChange函数可重用,你正在做一个受控的形式,所以首先你需要添加一个函数,将建立什么handleChange需要工作:

const parseEditorData = (content, editor) => {
//content is the current value of the text editor
// editor is an object that holds the html element that in this case is the text area where the name prop will be stored.
const { targetElm } = editor;
// This name value references the prop that you pass as textAreaName (content in your case)
const { name } = targetElm;
// This function returns an object that your handle change can parse correctly
return {
target: {
name,
value: content
}
};
};
现在您已经准备好了解析函数,您需要稍微更改一下Editor组件中的props:
<Editor
outputFormat='text'
init={{
height: 500,
width: 420,
menubar: false,
toolbar: 'undo redo | formatselect | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | help'
}}
onEditorChange={(content, editor) =>
handleChange(parseEditorData(content, editor))
}
value={formData.content}
textareaName="content"
/>

正如您所看到的,onEditorChange将使用从parseEditorData函数接收到的解析对象运行handleChange,此结果看起来与您正确运行handleChange所需的结果相似。最后但并非不重要的是,textAreaName道具将是您需要传递的对象,以保存formData对象中内容键的引用。

请检查这个沙盒来说明这个过程:https://codesandbox.io/s/still-river-2q6pf?file=/src/App.js: 840 - 862

最新更新