reactjs – ref-redux中ref和node引用了什么?

前端之家收集整理的这篇文章主要介绍了reactjs – ref-redux中ref和node引用了什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习 docs的react-redux,看不出下面的意思.参考部分指的是什么?和节点?从我看到的这个参考文献中没有使用过.在呈现之后,ref是否引用DOM上的子组件的节点(输入)?如果是这样,为什么不直接参考输入?
  1. import React from 'react'
  2. import { connect } from 'react-redux'
  3. import { addTodo } from '../actions'
  4.  
  5. let AddTodo = ({ dispatch }) => {
  6. let input
  7.  
  8. return (
  9. <div>
  10. <form onSubmit={e => {
  11. e.preventDefault()
  12. if (!input.value.trim()) {
  13. return
  14. }
  15. dispatch(addTodo(input.value))
  16. input.value = ''
  17. }}>
  18. <input ref={node => {
  19. input = node
  20. }} />
  21. <button type="submit">
  22. Add Todo
  23. </button>
  24. </form>
  25. </div>
  26. )
  27. }
  28. AddTodo = connect()(AddTodo)
  29.  
  30. export default AddTodo

解决方法

这是一个 ref callback attribute,其目的是获得对DOM元素/类组件的“直接访问”.使用ref你可以聚焦输入框,直接获取它的值或访问类组件的方法.

在这种情况下,它的目的是通过分配对输入变量的引用(let输入)来获取/更改输入的值 – 请参阅代码中的注释.

  1. let AddTodo = ({ dispatch }) => {
  2. let input // the input variable which will hold reference to the input element
  3.  
  4. return (
  5. <div>
  6. <form onSubmit={e => {
  7. e.preventDefault()
  8. if (!input.value.trim()) { // using the input variable
  9. return
  10. }
  11. dispatch(addTodo(input.value)) // using the input variable
  12. input.value = ''
  13. }}>
  14. <input ref={node => {
  15. input = node // assign the node reference to the input variable
  16. }} />
  17. <button type="submit">
  18. Add Todo
  19. </button>
  20. </form>
  21. </div>
  22. )
  23. }

猜你在找的JavaScript相关文章