React教程14:Refs
这篇React教程是关于React中的Refs概念。
ref 是用来指引某一个元素的。Refs 在DOM 调试或者需要添加methods到你的components中很有用。 但大多数情况,都不需要使用 Refs 。
使用 Refs
这个例子演示如何通过refs 来清空 input 文本框。clearInput 功能是用来查找元素中有 ref = “myInput” 的值,重设state 并在按钮点击后添加 focus。
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'));
当按钮被点击了, input 会被清空,并focus。
