react 使用 富文本编辑器并支持MD,同时支持<Form.Item/>的可控输入

61 篇文章 1 订阅
51 篇文章 2 订阅

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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值