问题描述和原因
antd 使用TextArea 最后一个字符删除不了,原因是value和onChange一起使用,删除最后一个字符,不会触发onChange事件
<TextArea
rows={6}
placeholder="请输入body示例"
value={bodyExample}
onChange={event => this.handleMaxRestoreUp(event)}
/>
解决方法
我的应用场景会请求接口先给TextArea赋值,直接用defaultValue,不能生效,查阅解决方法,给一个key值且和defaultValue值一样
<TextArea
key={bodyExample}
rows={6}
placeholder="请输入body示例"
value={bodyExample}
onChange={event => this.handleMaxRestoreUp(event)}
/>
优化和整体代码
上面的代码基本解决问题,不过TextArea赋值中,容易失焦。优化一下
state={
bodyExample: "",
sendBodyExample: "",
}
componentDidMount() {
this.setState({
bodyExample: '接口返回的值',
sendBodyExample: '接口返回的值'
});
}
handleMaxRestoreUp = (event: any) => {
if (event && event.target && event.target.value) {
let value = event.target.value;
this.setState(() => ({ sendBodyExample: value }));
}
};
sendRequest = () => {
const { sendBodyExample } = this.state
const param ={
body:sendBodyExample
}
API(param).then(res => {})
};
<TextArea
key={bodyExample}
rows={6}
placeholder="请输入body示例"
defaultValue={bodyExample}
onChange={event => this.handleMaxRestoreUp(event)}
/>
<Button type="primary" onClick={() => { this.sendRequest() }}> 提交 </Button>
当在Ant Design的TextArea组件中同时使用value和onChange属性时,删除最后一个字符不会触发onChange事件,导致无法删除。解决方法是在TextArea组件上添加一个与value相同的key属性。此外,可以优化代码结构,将初始值分配给state并在onChange事件中更新state,以确保组件更新。在提交时,从state获取值进行接口调用。
308

被折叠的 条评论
为什么被折叠?



