onSubmit是AddExpense组件如何从ExpenseForm检索数据?
数据不能从子级发送到父级,不是吗?
我对于在组件之间发送数据感到非常困惑?
AddExpensePage.js
import React from 'react'
import { connect } from 'react-redux'
import ExpenseForm from './ExpenseForm'
import { addExpense} from '../actions/expenses'
const AddExpensePage = (props) => {
return (
<div>
<h1>Add expense</h1>
<ExpenseForm
onSubmit={(expense)=>{
props.dispatch(addExpense(expense))
//redirect to page without refrshing
props.history.push('/')
}}
/>
</div>
)
}
export default connect()(AddExpensePage)
ExpenseForm.js
onSubmit=(e)=>{
e.preventDefault();
if(!this.state.description||!this.state.amount){
this.setState(()=>{
return {
error:'please provide a description and amount'
}
})
}else{
this.setState(() => {
return {
error: ''
}
})
this.props.onSubmit({
description:this.state.description,
amount:parseFloat(this.state.amount,10)*100,
createdAt:this.state.createdAt.valueOf(), //createdAt is a moment object
note:this.state.note
})
}
}
答案 0 :(得分:1)
由于有作为功能的道具,您可以将数据传递给父组件,在代码中onSubmit
就是这种情况。
在您的情况下,数据以对象的形式传递给onSubmit
道具。参见ExpenseForm.js
:
this.props.onSubmit({
description:this.state.description,
amount:parseFloat(this.state.amount,10)*100,
createdAt:this.state.createdAt.valueOf(), //createdAt is a moment object
note:this.state.note
})
此数据包含在expense
函数的onSubmit
参数中。参见AddExpensePage.js
:
<ExpenseForm
onSubmit={(expense)=>{
props.dispatch(addExpense(expense))
//redirect to page without refrshing
props.history.push('/')
}}
/>
换句话说,expense
是具有以下属性的对象:description
,amount
,createdAt
和note
,因为传递了什么作为this.props.onSubmit
中ExpenseForm.js
的参数。
有帮助吗?
此React文档页面将为您提供有关道具如何工作的大量详细信息:https://reactjs.org/docs/components-and-props.html#rendering-a-component。
答案 1 :(得分:0)
使用不能将数据子组件传递给父组件使用redux将数据传递到任何将子组件传递给父组件并将父组件传递给子组件的地方