学习React(24) - 介绍Refs的用法

    技术2026-08-22  10

    // RefsDemo.js 文件 import React, { Component } from 'react' class RefsDemo extends Component { constructor(props) { super(props) // 用到这个方法createRef() this.inputRef = React.createRef() // call back ref this.cbRef = null this.setCbRef = (element) => { this.cbRef = element } } componentDidMount() { if(this.cbDef) { this.cbRef.focus() } // this.inputRef.current.focus() // console.log(this.inputRef) } clickHandler = () => { alert(this.inputRef.current.value) } render() { return ( <div> <input type="text" ref={this.inputRef}/> <input type="text" ref={this.setCbRef}/> <button onClick={this.clickHandler}>Click</button> </div> ) } } export default RefsDemo

    在App.js 文件中

    // App.js 文件 import React from 'react'; import './App.css'; import RefsDemo from './RefsDemo'; function App() { return ( <div className="App"> <RefsDemo/> </div> ); } export default App;

    结果如下:

    当我在第一个方框里输入"world"时,点击Click按钮,就会弹出Alert框

    如果觉得不错的话,就用点赞来代替五星好评吧!

    Processed: 0.012, SQL: 9