+
80
-

请问react中useRef是干啥的?

请问react中useRef是干啥的?

网友回复

+
0
-

useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内保持不变。

示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="box"></div>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://cdn.bootcss.com/babel-standalone/7.0.0-beta.3/babel.js"></script>
  
  <script type="text/babel">
    const {useRef} = React
    function Compont() {
      const username = useRef()
      const password = useRef()
      const handleClick = () => {
        console.log('用户名:' + username.current.value)
        console.log('密码:' + password.current.value)
      }
      return(
        <div>
          用户名:<input type="text" ref={username} /> <br/>
          密码:<input type="password" ref={password} /> <br/>
          <buttonBfwOnClick={handleClick}>点击登入</button>
        </div>
      )
    }
    ReactDOM.render( <Compont/>, document.getElementById('box'))
  </script>
</body>
</html>

我知道答案,我要回答