react非受控組件useRef方法

效果圖如下:
在這裏插入圖片描述
代碼如下:

<!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/>
          <button onClick={handleClick}>點擊登入</button>
        </div>
      )
    }
    ReactDOM.render( <Compont/>, document.getElementById('box'))
  </script>
</body>
</html>
發佈了215 篇原創文章 · 獲贊 34 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章