1、表单

<Form.Item label={<div><span style={{ color: 'red' }}>*</span>标题</div>}>
          <div style={{ marginBottom: '4px' }}><Button type='primary' onClick={() => this.setState({ wordsVisible: true })}>插入动态词包</Button></div>
          <Form.Item name='title' rules={[{ validator: this.titleCheck }]}>
            <Input.TextArea ref={input => this.contentProps = input} autoSize={{ minRows: 8 }} placeholder='标题长度范围为6-30个字,添加多个标题请换行' />
          </Form.Item>
        </Form.Item>

{
        wordsVisible && <Modal visible={wordsVisible} title='公共词包' onOk={this.insert} onCancel={() => this.setState({ wordsVisible: false })} />
      }

2、插入判断

insert = () => {
    // 获取光标所在位置
    let index = this.contentProps.resizableTextArea.textArea.selectionStart
    const content = this.form.getFieldValue('title')
    const str = '我是插入语'
    const value = content ? content.slice(0, index) + str + content.slice(index) : str
    this.form.setFieldsValue({ title: value })
    this.timer = setTimeout(() => {
      // 光标移动到插入次的后面并进行form校验
      this.contentProps.focus()
      this.contentProps.resizableTextArea.textArea.setSelectionRange(index + str.length, index + str.length)
      this.setState({ wordsVisible: false })
      this.form.validateFields()
    }, 0)
  }

3、表单校验

titleCheck = (_, value) => {
    const arr = value.split('\n')
    return new Promise((resolve, reject) => {
      if (value) {
        const index = arr.findIndex(i => i?.length < 6 || i.length > 30)
        if (arr && index >= 0) {
          return reject(`第${index + 1}行的标题字数需要在6~30字之间`)
        }
        resolve()
      } else {
        reject('请输入标题')
      }
    })
  }

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐