此处的输入如何获得 .value 以及什么是 ref?
How does input here get a .value and what is a ref?
这里的输入如何得到.value
?它是如何从以下节点获取的:
<input ref={node => {
input = node
}} />
node
是输入标签中的 DOM 节点吗?
ref
到底是什么,为什么我们需要它来获取输入值?
我可以将 ref
放在任何 html 类型的标签上以获取 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 带有 Component then the node is an instance of Component,when ref an Element 时,节点是一个 DOMElement 实例。
- 你可以在任何地方
ref
,但反应建议 don't to overuse。
您有两种使用 ref 的方法。 ref with function & ref as attribute with string name。
react 提供 value
/check
来检索表单元素值。
这里的输入如何得到.value
?它是如何从以下节点获取的:
<input ref={node => {
input = node
}} />
node
是输入标签中的 DOM 节点吗?
ref
到底是什么,为什么我们需要它来获取输入值?
我可以将 ref
放在任何 html 类型的标签上以获取 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 带有 Component then the node is an instance of Component,when ref an Element 时,节点是一个 DOMElement 实例。
- 你可以在任何地方
ref
,但反应建议 don't to overuse。 您有两种使用 ref 的方法。 ref with function & ref as attribute with string name。
react 提供
value
/check
来检索表单元素值。