You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
745 B

2 years ago
  1. import React from 'react'
  2. import { createRef } from 'react'
  3. class Input extends React.Component {
  4. // 这个实例属性是可以定义的,语义化即可
  5. // createRef() 调用后可以返回一个容器,该容器可以存储被 ref 所表示的节点 就是说 input 这个 DOM 放在了 myRef 这个属性上
  6. msgRef = createRef()
  7. getValue = () => {
  8. // current.value 是指当前的 value 值
  9. console.log(this.msgRef.current.value)
  10. }
  11. render() {
  12. return (
  13. <>
  14. {/* 通过 ref 属性获取 msgRef */}
  15. <input type="text" ref={this.msgRef} />
  16. <button onClick={this.getValue}>获取输入框的值</button>
  17. </>
  18. )
  19. }
  20. }
  21. function App() {
  22. return <Input></Input>
  23. }
  24. export default App