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('请输入标题')
}
})
}