我正在学习
docs的react-redux,看不出下面的意思.参考部分指的是什么?和节点?从我看到的这个参考文献中没有使用过.在呈现之后,ref是否引用DOM上的子组件的节点(输入)?如果是这样,为什么不直接参考输入?
- import React from 'react'
- import { connect } from 'react-redux'
- import { addTodo } from '../actions'
- let AddTodo = ({ dispatch }) => {
- let input
- return (
- <div>
- <form onSubmit={e => {
- e.preventDefault()
- if (!input.value.trim()) {
- return
- }
- dispatch(addTodo(input.value))
- input.value = ''
- }}>
- <input ref={node => {
- input = node
- }} />
- <button type="submit">
- Add Todo
- </button>
- </form>
- </div>
- )
- }
- AddTodo = connect()(AddTodo)
- export default AddTodo
解决方法
这是一个
ref callback attribute,其目的是获得对DOM元素/类组件的“直接访问”.使用ref你可以聚焦输入框,直接获取它的值或访问类组件的方法.
在这种情况下,它的目的是通过分配对输入变量的引用(let输入)来获取/更改输入的值 – 请参阅代码中的注释.
- let AddTodo = ({ dispatch }) => {
- let input // the input variable which will hold reference to the input element
- return (
- <div>
- <form onSubmit={e => {
- e.preventDefault()
- if (!input.value.trim()) { // using the input variable
- return
- }
- dispatch(addTodo(input.value)) // using the input variable
- input.value = ''
- }}>
- <input ref={node => {
- input = node // assign the node reference to the input variable
- }} />
- <button type="submit">
- Add Todo
- </button>
- </form>
- </div>
- )
- }