我正在为富文本编辑器使用“react-draft-wysiwyg”库。我的问题是我能够获取值的 rawContentState 但无法将其转换为 html。为了转换 html,我正在使用“draftjs-to-html” ' library.Below 是我的组件,
公告.js
import React, { useEffect, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import dayjs from 'dayjs';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DesktopDateTimePicker } from '@mui/x-date-pickers/DesktopDateTimePicker';
import { DesktopDatePicker } from '@mui/x-date-pickers/DesktopDatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import {
Box,
Stack,
Button,
Select,
MenuItem,
FormGroup,
TextField,
Container,
InputLabel,
Typography,
FormControl,
FormControlLabel,
} from '@mui/material';
import Switch from '@mui/material/Switch';
import OpenInBrowserIcon from '@mui/icons-material/OpenInBrowser';
import NotificationsActiveIcon from '@mui/icons-material/NotificationsActive';
import EmailIcon from '@mui/icons-material/Email';
import SmsIcon from '@mui/icons-material/Sms';
import { ToastContainer, toast } from 'react-toastify';
// Importing the required components from react-draft-wysiwyg
import { EditorState, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import { draftToHtml } from 'draftjs-to-html';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { CreateNotices, ListNotices } from '../../services/notices';
function Announcements() {
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState([]);
const [isScheduleOn, setIsScheduleOn] = useState(false);
const [isBrowserOn, setIsBrowserOn] = useState(false);
const [isEmailOn, setIsEmailOn] = useState(false);
const [isSmsOn, setIsSmsOn] = useState(false);
const validationSchema = Yup.object({
channel: Yup.object().test({
name: "channel",
message: "Please select at least one channel",
test: (value) => {
return value.browserPush || value.email || value.sms;
},
}),
role: Yup.string().required("Role is required"),
title: Yup.string().required("Title/Subject is required"),
messageBody: Yup.string().required("Comment is required"),
expairyDateTime: Yup.string().required("expairyDate is required"),
});
const formik = useFormik({
initialValues: {
channel: {
browserPush: false,
email: false,
sms: false,
},
role: "",
title: "",
messageBody: "",
messageContentWithHtml: EditorState.createEmpty(),
expairyDateTime: '',
ScheduleDateTime: '',
},
validationSchema,
onSubmit: async (values) => {
// console.log('output1', values.messageContentWithHtml.getCurrentContent().getPlainText());
const rawContentState = convertToRaw(values.messageContentWithHtml.getCurrentContent());
const html = draftToHtml(rawContentState);
console.log(html)
},
});
const getNotices = async () => {
setTimeout(async () => {
try {
const apiRes = await ListNotices();
if (apiRes.status === 200) {
setLoading(true);
setFormData(apiRes?.data?.data || []);
} else {
setLoading(false);
toast.error(apiRes?.data?.message || 'Something went wrong!, Please try again.', {
position: toast.POSITION.BOTTOM_LEFT
})
}
} catch (err) {
setLoading(false);
toast.error('Something went wrong!, Please try again.', {
position: toast.POSITION.BOTTOM_LEFT
})
}
}, 500)
};
// useEffect(() => {
// getNotices();
// }, [])
const currentYear = dayjs().year();
// const minDate = `${currentYear}-01-01`;
const minDate = dayjs();
const maxDate = new Date(2026, 11, 31); // current year
const { channel } = formik.values;
return (
<>
<Helmet>
<title>Announcement </title>
</Helmet>
<Container maxWidth="lg">
<Typography mb={5} variant="h4" gutterBottom>
Announcements
</Typography>
<Stack direction={'row'} spacing={2}>
<Box width={'40%'}
bgcolor={"white"}
whiteSpace="normal"
px={2}
pt={2}
sx={{
// width: { xs: '100%', sm: '100%', md: '40%', lg: '40%' },
boxShadow: '0px 0px 5px -2px',
borderRadius: '10px',
}}
>
<Typography variant='h4' my={2} >Channels</Typography>
<Stack direction="row" spacing={2} alignItems="center" justifyContent="space-between">
<Box display={'flex'}>
<OpenInBrowserIcon style={{ color: "#9e9e9e" }} />
<Typography ml={1} variant="body1" color="inherit">Browser Push</Typography>
</Box>
<Box>
<Switch checked={channel?.browserPush} onChange={() => formik.setFieldValue('channel.browserPush', !channel.browserPush)} />
</Box>
</Stack>
<Stack direction="row" spacing={2} alignItems="center" justifyContent="space-between">
<Box display={'flex'}>
<EmailIcon style={{ color: "#9e9e9e" }} />
<Typography ml={1} variant="body1" color="inherit">Email</Typography>
</Box>
<Box>
<Switch checked={channel?.email} onChange={() => formik.setFieldValue('channel.email', !channel.email)} />
</Box>
</Stack>
<Stack direction="row" spacing={2} alignItems="center" justifyContent="space-between">
<Box display={'flex'}>
<SmsIcon style={{ color: "#9e9e9e" }} />
<Typography ml={1} variant="body1" color="inherit">SMS</Typography>
</Box>
<Box>
<Switch checked={channel?.sms} onChange={() => formik.setFieldValue('channel.sms', !channel.sms)} />
</Box>
</Stack>
{formik.touched.channel && !formik.values.channel.browserPush && !formik.values.channel.email && !formik.values.channel.sms && (
<Typography color="error">Please select at least one channel</Typography>
)}
</Box>
<Box
px={2}
py={2}
width={"100%"}
bgcolor={"white"}
sx={{
// width: { xs: '100%', sm: '100%', md: '40%', lg: '40%' },
boxShadow: '0px 0px 5px -2px',
borderRadius: '10px',
}}
>
<form onSubmit={formik.handleSubmit}>
<Stack
mx={2}
direction={'column'}
spacing={2}
>
<Typography variant='h4' my={2} >Announcement Details</Typography>
<Box width={'100%'} mb={2}>
<FormControl fullWidth>
<InputLabel id="role">Role</InputLabel>
<Select
sx={{
width: '100%',
}}
labelId="role"
id="role"
name="role"
label="Role"
value={formik.values.role}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
error={formik.touched.role && Boolean(formik.errors.role)}
helperText={formik.touched.role && formik.errors.role}
>
<MenuItem value='Administrator'>Administrator</MenuItem>
<MenuItem value='Alumni'>Alumni</MenuItem>
</Select>
</FormControl>
{formik.touched.role && formik.errors.role && <p style={{ color: 'red', marginTop: '5px', marginBottom: '-15px' }}>{formik.errors.role}</p>}
</Box>
<Box mb={2}>
<TextField
sx={{ width: '100%' }}
label="Title/Subject"
id="title"
name="title"
type="text"
value={formik.values.title}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
error={formik.touched.title && Boolean(formik.errors.title)}
/>
{formik.touched.title && formik.errors.title && <p style={{ color: 'red', marginTop: '5px', marginBottom: '-15px' }}>{formik.errors.title}</p>}
</Box>
<Box mb={2}>
<TextField
sx={{
width: '100%',
}}
id="outlined-comment"
label="Add a comment"
type="text"
multiline
rows={4}
maxRows={6}
name="messageBody"
value={formik.values.messageBody}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
error={formik.touched.messageBody && Boolean(formik.errors.messageBody)}
autoComplete="off"
/>
{formik.touched.messageBody && formik.errors.messageBody && <p style={{ color: 'red', marginTop: '5px', marginBottom: '-15px' }}>{formik.errors.messageBody}</p>}
</Box>
{channel?.email && (
<Box mb={2}>
<Editor
editorState={formik.values.messageContentWithHtml}
onEditorStateChange={(editorState) => {
formik.setFieldValue('messageContentWithHtml', editorState);
}}
editorStyle={{
border: '1px solid #ccc',
boxShadow: '0 0 5px rgba(0, 0, 0, 0.1)',
height: '200px',
maxWidth: '80vw',
}}
/>
</Box>
)}
<Box mb={2}>
<Box mb={2}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DesktopDateTimePicker
label="Expairy Date and Time"
inputFormat="DD/MM/YYYY HH:mm:ss"
value={formik.values?.expairyDateTime}
onChange={(newValue) => {
formik.setFieldValue("expairyDateTime", newValue);
formik.setFieldTouched("expairyDateTime", true);
}}
renderInput={(params) => (
<TextField
sx={{
width: "100%",
}}
{...params}
name="expairyDateTime"
onBlur={formik.handleBlur}
error={
formik.errors.expairyDateTime &&
formik.touched.expairyDateTime
}
/>
)}
minDateTime={minDate}
maxDate={maxDate}
/>
</LocalizationProvider>
{formik.touched.expairyDateTime && formik.errors.expairyDateTime && <p style={{ color: 'red', marginTop: '5px', marginBottom: '-15px' }}>{formik.errors.expairyDateTime}</p>}
</Box>
</Box>
<Box mb={2}>
<FormGroup>
<FormControlLabel control={<Switch checked={isScheduleOn} onChange={(event) => setIsScheduleOn(event.target.checked)} />} label="Schedule" />
</FormGroup>
</Box>
{isScheduleOn && (
<Box mb={2}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DesktopDateTimePicker
label="Schedule Date and Time"
inputFormat="DD/MM/YYYY HH:mm:ss"
value={formik.values?.ScheduleDateTime}
onChange={(newValue) => {
formik.setFieldValue("ScheduleDateTime", newValue);
formik.setFieldTouched("ScheduleDateTime", true);
}}
renderInput={(params) => (
<TextField
sx={{
width: "100%",
}}
{...params}
name="ScheduleDateTime"
onBlur={formik.handleBlur}
error={
formik.errors.ScheduleDateTime &&
formik.touched.ScheduleDateTime
}
/>
)}
minDateTime={minDate}
maxDate={maxDate}
/>
</LocalizationProvider>
</Box>
)}
<Stack py={1}>
<Box ml={'auto'}>
<Button type='submit' variant="contained" sx={{
backgroundColor: "rgb(0, 171, 85)"
}}>
Publish
</Button>
</Box>
</Stack>
</Stack>
</form>
</Box>
</Stack>
<ToastContainer />
</Container>
</>
)
}
export default Announcements
检查这个并提出解决方案或者你可以建议我应该使用哪个文本编辑器,提前致谢......