React的ref有3種用法:react
1. 字符串(已廢棄)
2. 回調函數
3. React.createRef()ios
老規矩先上代碼npm
新增pages/Ref.js文件axios
import React from 'react'; export default class Ref extends React.Component{ constructor(props){ super(props); this.ref3 = React.createRef(); } componentDidMount(){ console.log(this.refs.input); console.log(this.ref2); console.log(this.ref3); this.refs.input.value = 'ref1'; this.ref2.value = 'ref2'; this.ref3.current.value = 'ref3'; } render(){ return ( <div> {/*ref1*/} <input ref="input" />
{/*ref2*/} <input ref={(input) => {this.ref2 = input}} />
{/*ref3*/} <input ref={this.ref3} />
</div>
) } }
route/index.js修改以下react-router
import React from 'react'; import {Switch, Route} from "react-router-dom"; import asyncComponent from '../lazy'; import Home2 from '../pages/Home2'; import OnePage from '../pages/OnePage'; import TwoPage from '../pages/TwoPage'; import This from '../pages/This'; import Mount from '../pages/Mount'; import HooksTest1 from '../hooks/test1'; import AxiosTest from '../pages/AxiosTest'; import Refs from '../pages/Ref'; //import HooksUseState from '../hooks/useState';
const HooksUseState = asyncComponent(() => import ('../hooks/useState')); const Routers = ( <Switch>
<Route path="/" exact component={Home2} />
<Route path="/onePage" component={OnePage} />
<Route path="/twoPage/:id" component={TwoPage} />
<Route path="/this" component={This} />
<Route path="/mount" component={Mount} />
<Route path="/hooksTest1" component={HooksTest1} />
<Route path="/axiosTest" component={AxiosTest} />
<Route path="/refs" component={Refs} />
<Route path="/hooksUseState" component={HooksUseState} />
</Switch>
); export default Routers
啓動項目npm start,打開http://localhost:3000/#/refsdom
查看控制檯打印的結果 我代碼裏有註釋一、二、3,打印也有一、二、3應該很清楚吧async
如今大部分都用第三種,由於你點開第三種的小箭頭會顯示不少屬性,隨便用 大部分都是你認識的Dom屬性、事件和方法函數