antd 3.10.0的TextArea不支援顯示總字數和當前字數
阿新 • • 發佈:2021-11-03
antd 3.10.0的TextArea不支援顯示總字數和當前字數,專案是遺留程式碼,貿然升級成antd 4.x的風險略大,不可控,遂決定擴充套件TextArea的功能新增上對當前字數和總字數的支援。
原理並不複雜,antd 3.x的TextArea還是以class形式定義的,直接繼承這個class就行,然後加上顯示當前字數和總字數的div以及對應的css。
js:
import React from 'react'; import { Input } from 'antd'; import styles from './index.less'; const { TextArea } = Input; class CountedTextarea extends TextArea { valueLength() {if (this.state.value && this.state.value.length) { return this.state.value.length; } return 0; } render() { return ( <div className={styles.countedtextareaWrapper}> {super.render()} <div className={styles.border} /> <span className={styles.countWrapper}> <span>{this.valueLength()}</span>/<span>{this.props.maxLength}</span> </span> </div> ); } } export default CountedTextarea;
less:
.countedtextareaWrapper { position: relative; z-index: 1; .border { transition: all 0.2s; top: 0; left: 0; position: absolute; width: 100%; height: calc(100% + 32px); border: 1px solid #d9d9d9; border-radius: 4px; z-index: -1; } textarea { border: none; margin: 1px; width: calc(100% - 2px); resize: none; &:focus { box-shadow: none; + .border { border-color: #40a9ff; box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2); } } } .countWrapper { position: absolute; bottom: -22px; right: 10px; font-family: PingFangSC-Regular; font-size: 14px; color: #c1c1c1; letter-spacing: 0; font-weight: 400; span { font-family: PingFangSC-Regular; font-size: 14px; color: #c1c1c1; letter-spacing: 0; font-weight: 400; } } } :global(.countedItem) { .countWrapper { bottom: -34px; } :global(.has-error) { position: relative; .countedtextareaWrapper { :global(.ant-input) { + .border { border-color: #ff4d4f; } &:focus, &:hover { border: none; box-shadow: none; + .border { box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2); } } } } } } :global { .countedItem { position: relative; margin-bottom: 60px; &.ant-form-item-with-help { margin-bottom: 41px; } .ant-form-explain { top: 36px; position: relative; } } }
這樣的話,支援在FormItem裡使用此CountedTextarea 元件,需要在FormItem 上加上className="countedItem" 即可。