react+antd输入框值想在点击清空按钮的时候清空怎么办()

本文介绍了在React中如何清除Antd输入框的值,讨论了旧版API的字符串引用问题及其潜在风险,提供了新版API的解决方案,并链接了官方解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

废话不多说先上一版解决办法

clear(){
	this.refs.myInput.state.value = '';
}
<Search size="large" defaultValue="" style={{ width: 400 }} ref="myInput" />
<Button onClick={() => {this.clear()}}>清空<Button>                                

这个虽然可以清空,但是如果你遇到这个问题
在这里插入图片描述
这是因为如果以前使用过React,那么可能会熟悉一个较旧的API,该API的ref属性是一个字符串,例如"textInput",并且DOM节点的访问方式是this.refs.textInput。我们建议不要这样做,因为字符串引用存在一些问题,被认为是旧问题,并且很可能会在将来的发行版中删除。
官方解释点这里
那么改版之后的代码是这样

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
  }

  clear() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    //可以打印一下试试
    //console.log(this.textInput);
    this.textInput.current.state.value = '';
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
       <Search size="large" defaultValue="" style={{ width: 400 }} ref={this.textInput} />
       <Button onClick={() => {this.clear()}}>清空<Button>
    );
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值