1.分析
<Form.Item label="id" name="id" hidden>
<Input />
</Form.Item>
在react ant 使用中,我们可以看到,Input 输入变化后,值会自动绑定到form实例上,同时,form set值以后,Input 也会跟着变化。这里面Input 默认挂载了两个属性value和onChange,从而做到了双向绑定,所以我们也可以实现一个这个的自定义可控组件
2.实现
2.1引入插件
npm install react-markdown-editor-lite markdown-it
2.2 封装组件
import React, { useEffect, useState } from 'react';
import MdEditor from 'react-markdown-editor-lite';
import MarkdownIt from 'markdown-it';
import 'react-markdown-editor-lite/lib/index.css';
// 初始化 markdown 解析器
const mdParser = new MarkdownIt();
export default ({ value, view, readOnly, onChange, ...resetProps }: PropsType) => {
const [content, setContent] = useState(value);
useEffect(() => {
setContent(value);
}, [value]);
const handleEditorChange = ({ html, text }) => {
setContent(text);
onChange?.(text);
};
if (!view) {
view = {
menu: false,
md: false,
html: true,
};
}
return (
<MdEditor
value={content}
style={{ height: '500px' }}
renderHTML={(text) => mdParser.render(text)}
onChange={handleEditorChange}
readOnly={readOnly ?? false}
view={view}
{...resetProps}
/>
);
};
interface PropsType {
value?: string;
readOnly?: boolean;
2.2 使用
<Form.Item
label="公共内容"
name="noticeContent"
rules={[{ required: true }]}
style={{ marginBottom: '8px' }}
>
<WebEditor />
</Form.Item>