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')
);
|