Log:2021-12-06

1.学习ref的用法

import React, { useState,useEffect,useRef } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Button, Tabs } from 'antd';
import $ from 'jquery'
import { element } from 'prop-types';


class Counter extends React.Component{
  constructor(props){
    super(props);
    this.myRef=React.createRef();
    this.myRef2=React.createRef();
    this.clickFunction=this.clickFunction.bind(this);
    this.clickFunction2=this.clickFunction2.bind(this);
  }

  clickFunction(){
    this.myRef.current.focus();
  }

  clickFunction2(){
    this.myRef2.current.focus();
  }

  render(){
    return(
      <div>
        <input type="text" ref={this.myRef}/>
        <input type="text" ref={this.myRef2}/>
        <input type="button" onClick={this.clickFunction} value="click me"/>
        <input type="button" onClick={this.clickFunction2} value="click him"/>
      </div>

    );
  }
}

class Demo extends React.Component{
  constructor(props){
    super(props);
    this.myRef=React.createRef();

  }

  componentDidMount(){

    this.myRef.current.clickFunction2();
  }

  render(){
    return (

      <Counter ref={this.myRef}/>
    );
  }
}

function Demo2()
{

  const yourRef=useRef(null);
  function handleClick(){
    yourRef.current.focus();
  }
  return(
    <div>
      <input type="text" ref={yourRef}/>
      <input type="button" onClick={handleClick} value="click me"/>

    </div>

  );
}

class CustomTextInput extends React.Component {
  constructor(props){
    super(props);
    this.testInputText=null;
    this.setTestRef= element => {
      this.testInputText=element;
    }

    this.myClick= () => {
      if(this.testInputText){
        this.testInputText.focus();
      }
    }



  }

  componentDidMount() {
    // 组件挂载后,让文本框自动获得焦点
    this.myClick();
  }

  render(){
    return (
      <div>
      <input type="text" ref={this.setTestRef}/>
      <input type="button" value="focus me" onClick={this.myClick}/>
      </div>

    );
  }
}

ReactDOM.render(
  <CustomTextInput  />,
  document.getElementById('root')
);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值