react--ref操作虚拟Dom

React的ref有3种用法:

1. 字符串(已废弃)
2. 回调函数
3. React.createRef()

老规矩先上代码

新增pages/Ref.js文件

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修改如下

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/#/refs

查看控制台打印的结果 我代码里有注释1、2、3,打印也有1、2、3应该很清楚吧

现在大部分都用第三种,因为你点开第三种的小箭头会显示很多属性,随便用 大部分都是你认识的Dom属性、事件和方法

猜你喜欢

转载自www.cnblogs.com/huangjie2018/p/10719913.html
0条评论
添加一条新回复