我正在使用formik
我的表格。我想react-draft-wysiwyg
用formik实现编辑器。但是,在我的情况下,我发现了以下警告。
Warning: Formik called `handleBlur`, but you forgot to pass an `id` or `name` attribute to your input:
因此,我认为,如果它有验证问题,我将无法显示错误,并且如果我移动到下一个表单并返回到我在编辑器上放置内容的表单,状态也不会保留。
这是对这些问题负责的警告还是我错过了一些重要的事情?
这是我尝试绑定formik
的方式react-draft-wysiwyg
import React from "react";
import styled from "styled-components";
import { Editor } from "react-draft-wysiwyg";
import htmlToDraft from "html-to-draftjs";
import draftToHtml from "draftjs-to-html";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
const EditorField = ({
input,
meta,
field,
form,
label,
placeholder,
labelCss
}) => {
const [active, setActive] = React.useState();
const [editorState, setEditorState] = React.useState(
EditorState.createEmpty()
);
React.useEffect(() => {
if (form.dirty) {
return;
}
if (!field.value) {
return;
}
const contentBlock = htmlToDraft(field.value);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(
contentBlock.contentBlocks
);
const editorState = EditorState.createWithContent(contentState);
setEditorState(editorState);
}
}, [field.value, form.dirty]);
const onEditorStateChange = editorState => {
changeValue(editorState);
};
const changeValue = editorState => {
setEditorState(editorState);
form.setFieldValue(
field.name,
draftToHtml(convertToRaw(editorState.getCurrentContent()))
);
};
const hasError = form.touched[field.name] && form.errors[field.name];
return (
<>
<Wrapper>
{label && (
<Label isActive={active} css={labelCss}>
{label}
</Label>
)}
<Editor
editorState={editorState}
wrapperClassName="wrapper-class"
editorClassName="editor-class"
toolbarClassName="toolbar-class"
onEditorStateChange={editorState => onEditorStateChange(editorState)}
placeholder={placeholder}
toolbar={{
options: [
"inline",
"blockType",
"fontSize",
"fontFamily",
"list",
"textAlign",
"link",
"embedded",
"remove",
"history"
]
}}
name={field.name}
id={field.name}
onFocus={() => setActive(true)}
onBlur={e => {
setActive(false);
field.onBlur(e);
}}
/>
{!!hasError && <Error>{hasError}</Error>}
</Wrapper>
</>
);
};
export default EditorField;
const Wrapper = styled.div``;
渲染表单时,我正在执行以下操作
<Field
component={EditorField}
name="article"
label="Write an article"
placeholder="content here"
/>
我从服务器获得的数据显示在编辑器上。