类似document.queryselector();
方法1:old version 每次render都focus当前的inputElement; 将input的ref传入this.inputElement;
import React, { Component } from 'react'; // import './Person.css'; import classes from './person.module.css'; import withClass from '../../../hoc/WithClass'; import Aux from '../../../hoc/Auxiliary'; import PropTypes, { number } from 'prop-types'; class Person extends Component{ componentDidMount(){ this.inputElement.focus(); //每次render都focus当前的inputElement } render(){ console.log('person redering') return( <React.Fragment> <p>I Am a person!</p> <p onClick = {this.props.click}>{this.props.name}</p> <p>i'm {this.props.age}</p> <p>{this.props.children}</p> <input ref={(inputEl)=>{this.inputElement = inputEl}} //将input的ref传入this.inputElement type="text" onChange={this.props.changed} value={this.props.name}/> </React.Fragment> ) } }; Person.propTypes ={ click: PropTypes.func, age:PropTypes.number, name:PropTypes.string, changed:PropTypes.func }; export default withClass(Person,classes.Person);方法2:new Version
import React, { Component } from 'react'; // import './Person.css'; import classes from './person.module.css'; import withClass from '../../../hoc/WithClass'; import Aux from '../../../hoc/Auxiliary'; import PropTypes, { number } from 'prop-types'; class Person extends Component{ constructor(props){ super(props); this.inputElementEl = React.createRef(); //每次调用建立一个ref } componentDidMount(){ this.inputElementEl.current.focus(); //对当前ref进行focus操作; } render(){ console.log('person redering') return( <React.Fragment> <p>I Am a person!</p> <p onClick = {this.props.click}>{this.props.name}</p> <p>i'm {this.props.age}</p> <p>{this.props.children}</p> <input ref ={this.inputElementEl} //将建立的ref赋给input type="text" onChange={this.props.changed} value={this.props.name}/> </React.Fragment> ) } }; Person.propTypes ={ click: PropTypes.func, age:PropTypes.number, name:PropTypes.string, changed:PropTypes.func }; export default withClass(Person,classes.Person);类似上面的方法2
<div className={Cssclasses.Cockpit}> <h1>{props.title}</h1> <p className={classes.join(' ')}>It is working!</p> <button ref={toggleBtnRef} className={btnClass} onClick={props.clicked}>Switch name </button> </div>注意点 调用current.event时要在useEffect()中,因为外面还未render代码,无法得到ref;
const toggleBtnRef = React.createRef(null); // toggleBtnRef.current.click();//太早了,还没render button useEffect(()=>{ //每次update都会被调用 console.log('[Cockpit.js] useeffect'); //Http request... toggleBtnRef.current.click(); return ()=>{ console.log('[Cock.js] cleanup wordk in useEffect'); } },[]); //传入作用与的对象——persons改变,调用effect //空array则只run开始那一次