【发布时间】:2017-01-31 19:50:43
【问题描述】:
我有一个简单的 React 组件,它有两个输入并分派一个操作以使用输入值将项目添加到目录中。
# components/addProduct.jsx
import React from 'react'
import { connect } from 'react-redux'
const AddProduct = ({
onClick
}) => {
let title, price
return (
<form
onSubmit= { (e) => {
e.preventDefault()
}}
>
Title: <input ref={ node => {title = node;}} type="text"/><br />
Price: <input ref={ node => {price = node;}} type="text"/><br />
<button onClick={onClick}>Create New Product</button>
</form>
)
}
function mapDispatchToProps(dispatch) {
return {
onClick: () => {
console.log("Firing on click for button")
console.log(this) # => mapToPropsProxy
console.log(AddProduct.refs) # => undefined
dispatch({ # This will be a call to addProduct(title, price) later
type: "ADD_PRODUCT",
title: this.refs.title.value, # ???
price: this.refs.price.value
})
}
}
}
export default connect(null, mapDispatchToProps)(AddProduct)
我无法访问我在 AddProduct 组件中声明的引用。这很直观; AddProduct 直到connect 第一次使用mapDispatchToProps 解析并被导出时才真正存在。
那么如何访问输入值?我的架构是否不正确?
【问题讨论】:
-
我知道我可以将调度移动到组件中,但如果我理解正确,我应该将 RENDERING 与 LOGIC 分开