ref用于返回到所述元素的引用。Refs大多數(shù)情況下應(yīng)避免使用它們,但是,當(dāng)我們需要DOM測量或向組件中添加方法時,它們可能很有用。
下面的示例顯示如何使用引用清除輸入字段。ClearInput函數(shù)使用ref = "myInput"值搜索元素,重置狀態(tài),并在單擊按鈕后對其添加焦點。
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;import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));一旦按下按鈕,輸入將被清除和焦點。