废话不多说先上一版解决办法
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>
);
}
}