Skip to content

Commit 407c33c

Browse files
author
liyuan-meng
committed
🐛[Input.Textarea]解决Textarea组件设置 resize 为 true 时,控制宽高变化,计数器样式异常的问题
1 parent 4d0cca2 commit 407c33c

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

src/components/input/demos/textarea.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export default function InputDemo() {
3232
<div>
3333
<Input.Textarea placeholder="请输入文案,最多10个字符" style={{ width: 400 }} autoSize maxLength={10} hasCounter />
3434
<br />
35-
<Input.Textarea placeholder="请输入文案,高度最小3行,最大5行" rows={4} resize />
35+
<Input.Textarea placeholder="请输入文案,高度最小3行,最大5行" rows={4} resize hasCounter maxLength={10}/>
3636
<br />
3737
<Input.Textarea placeholder="请输入文案,高度可自适应" autoSize minRows={2} />
3838
<br />

src/components/input/textarea.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from 'react';
1+
import React, { createRef } from 'react';
22
import PropTypes from 'prop-types';
33
import classnames from 'classnames';
44
import { noop, omit, prefixCls } from '@utils';
@@ -115,6 +115,8 @@ export default class Textarea extends React.PureComponent {
115115
onKeyDown: noop,
116116
};
117117

118+
ref = createRef();
119+
118120
static getDerivedStateFromProps({ value }) {
119121
if (value !== undefined) {
120122
return { value };
@@ -140,10 +142,25 @@ export default class Textarea extends React.PureComponent {
140142

141143
componentDidMount() {
142144
this.calcAutoHeight();
145+
146+
const textArea = this.ref?.current?.querySelector('textarea');
147+
// 创建一个观察者对象
148+
this.observer = new window.MutationObserver((mutations) => {
149+
mutations.forEach((mutation) => {
150+
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
151+
this.ref.current.style.width = `${textArea.clientWidth}px`;
152+
}
153+
});
154+
});
155+
// 观察者的配置(观察属性变化)
156+
const config = { attributes: true };
157+
// 传入目标节点和观察选项并开始观察
158+
this.observer.observe(textArea, config);
143159
}
144160

145161
componentWillUnmount() {
146162
destory();
163+
this.observer.takeRecords();
147164
}
148165

149166
onKeyDown = (evt) => {
@@ -204,6 +221,7 @@ export default class Textarea extends React.PureComponent {
204221

205222
return (
206223
<div
224+
ref={this.ref}
207225
className={`${prefixCls}-input-textarea-wrapper`}
208226
style={wrapperStyle}
209227
>

0 commit comments

Comments
 (0)