React 支持一種非常特殊的屬性 Ref ,可以用來綁定到 render() 輸出的任何組件上 import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; imp ...
React 支持一種非常特殊的屬性 Ref ,可以用來綁定到 render() 輸出的任何組件上
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import * as serviceWorker from './serviceWorker'; class Focus extends Component{ constructor(props){ super(props); this.focusFn=this.focusFn.bind(this); } focusFn(){ this.refs.myInput.focus(); } render(){ return( <div> <input type="text" ref="myInput" /> <br/> <button onClick={this.focusFn}>點我</button> </div> ) } } ReactDOM.render( <div> <Focus /> </div>, document.getElementById('example') ); serviceWorker.unregister();