【发布时间】:2021-08-07 07:07:39
【问题描述】:
我正在尝试将我在编辑器中键入的 html 内容从编辑器组件(子)获取到父级,以便我可以将表单与编辑器的内容一起保存到我的数据库中。
我尝试将 getContent 函数作为道具发送到编辑器(子)并从编辑器取回内容,但我不断收到错误消息,显示 getContent is not a function。
这样做的正确方法是什么,以便我可以将 html 内容从编辑器获取到父组件?
Editor.js(子)
import { useState } from 'react';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import './RichTextEditor.css';
const Editor = (getContent) => {
const [editorState, setEditorState] = useState(() =>
EditorState.createEmpty()
);
const handleEditorChange = (state) => {
setEditorState(state);
sendContent();
};
const sendContent = () => {
getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())));
};
return (
<div>
<Editor
editorState={editorState}
onEditorStateChange={handleEditorChange}
wrapperClassName="wrapper-class"
editorClassName="editor-class"
toolbarClassName="toolbar-class"
/>
<textarea value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}></textarea>
</div>
);
};
export default Editor;
CreateBulletin(父级)
import { useEffect, useState } from 'react'
import { Button, Col, Row } from 'react-bootstrap'
import Editor from '../Editor/Editor'
const AddBulletin = () => {
const [title, setTitle] = useState ('')
const [htmlContent, setHtmlContent] = useState('')
const getContent = (htmlContentProp) => {
setHtmlContent(htmlContentProp);
console.log(htmlContentProp);
}
const onSubmit = (e) => {
e.preventDefault();
if (!title) {
alert('Please add a title')
return
}
onAdd({ title, htmlContent })
setTitle('')
setHtmlContent('')
}
return (
<Row>
<Col xs={12} md={8}>
<form className='add-form' onSubmit={ onSubmit}>
<div className='form-control bulletin'>
<label>Title</label>
<input type='text' placeholder='Insert your title here...' style={{width: '100%'}}
value={title} onChange={(e) => setTitle(e.target.value)} />
</div>
<div className='form-control bulletin'>
<label>Content</label>
<Editor getContent={getContent} />
</div>
<Button as="input" type="submit" value="Submit" />
<Button variant="outline-danger">Cancel</Button>
</form>
</Col>
</Row>
)
}
export default AddBulletin
【问题讨论】:
标签: reactjs