ref
用于返回元素的引用。在大多数情况下应该避免使用refs
,但是当我们需要进行dom测量或向组件添加方法时,它们可能非常有用。
以下示例显示如何使用ref
来清除输入字段。 clearinput
函数搜索具有ref = "myinput"
值的元素,重置状态,并在点击按钮后添加焦点。
文件:app.jsx -
import react from 'react';
import reactdom from 'react-dom';
class app extends react.component {
constructor(props) {
super(props);
this.state = {
data: ''
}
this.updatestate = this.updatestate.bind(this);
this.clearinput = this.clearinput.bind(this);
};
updatestate(e) {
this.setstate({data: e.target.value});
}
clearinput() {
this.setstate({data: ''});
reactdom.finddomnode(this.refs.myinput).focus();
}
render() {
return (
<div>
<input value = {this.state.data} onchange = {this.updatestate}
ref = "myinput"></input>
<button onclick = {this.clearinput}>clear</button>
<h4>{this.state.data}</h4>
</div>
);
}
}
export default app;
文件:main.js -
import react from 'react';
import reactdom from 'react-dom';
import app from './app.jsx';
reactdom.render(<app/>, document.getelementbyid('app'));
当按钮被点击,输入框将被清除并处于焦点状态。