MST
星途 面试题库

面试题:React中如何使用Refs操作DOM元素

请阐述在React中使用Refs操作DOM元素的基本步骤,并给出一个简单示例,例如获取一个input输入框的值。
14.1万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

基本步骤

  1. 创建Ref对象:使用React.createRef()(在类组件中)或者useRef Hook(在函数组件中)创建一个Ref对象。
  2. 关联Ref对象到DOM元素:通过在需要操作的DOM元素上设置ref属性,将创建的Ref对象传递给它。
  3. 使用Ref对象操作DOM:在合适的时机,通过Ref对象访问关联的DOM元素,进而操作它。

示例 - 类组件

import React, { Component } from 'react';

class InputComponent extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  handleClick = () => {
    const inputValue = this.inputRef.current.value;
    console.log('Input value is:', inputValue);
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.inputRef} />
        <button onClick={this.handleClick}>Get Value</button>
      </div>
    );
  }
}

export default InputComponent;

示例 - 函数组件

import React, { useRef } from 'react';

const InputComponent = () => {
  const inputRef = useRef(null);

  const handleClick = () => {
    const inputValue = inputRef.current.value;
    console.log('Input value is:', inputValue);
  }

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Get Value</button>
    </div>
  );
}

export default InputComponent;