refs提供了一种方式,允许我们访问Dom节点或在render方法中创建的react元素

1. 通过回调函数形式

import React from 'react'

export default function login(props) {
  let input1 = ''

  function getVal() {
    console.log(input1.value)
  }

  return (
    <div>
      <input
        type="text"
        ref={(ipt) => {
          input1 = ipt
        }}
      />
      <button onClick={getVal}>获取input的值</button>
    </div>
  )
}

2. 函数式组件使用 useRef(),我试了好几次,发现只能在App.js文件中生效,不知道你们是不是这种情况

import React, { useRef } from 'react'

function App() {
  let hh = useRef(null)

  function getValue() {
    // hh.current就是获取的dom元素
    console.log(hh.current.value)
  }

  return (
    <div className="App">
      <input type="text" ref={hh} />
      <button onClick={getValue}>点击获取值</button>
    </div>
  )
}

export default App

 

原文链接:https://blog.csdn.net/qq_52845451/article/details/127098763

最后修改:2023 年 10 月 30 日
如果觉得我的文章对你有用,请随意赞赏