我有组件ExpenseForm
class ExpenseForm extends Component {
state = {
description: '',
amount: '',
note: '',
createdAt: moment(),
calendarFocused: false,
error: ''
};
onInputChange = (e) => {
const prop = e.target.name;
const val = e.target.value;
if(prop === 'amount') {
if(!val || val.match(/^\d{1,}(\.\d{0,2})?$/)) {
this.setState(() => ({ [prop]:val }));
}
} else {
this.setState(() => ({ [prop]:val }));
}
};
onDateChange = (createdAt) => {
if(createdAt) {
this.setState(() => ({createdAt}));
}
};
onFocusChange = ({focused}) => {
this.setState(() => ({calendarFocused: focused}))
};
onFormSubmit = (e) => {
e.preventDefault();
const { description, amount, note, createdAt } = this.state;
if(!description || !amount) {
this.setState(() => ({error: 'Please provide description and amount'}));
} else {
this.setState(() => ({error: ''}));
console.log(this.props.onSubmit) //<<< here i get undefined
this.props.onSubmit({
description,
amount: parseFloat(amount, 10) * 100,
createdAt: createdAt.valueOf(),
note
});
}
};
render() {
console.log(this.props) //<<< here I see the object with the prop onSubmit, where lies the function onEditSubmit
return (
<div>
<h1>Expense Form</h1>
{this.state.error && <p>{this.state.error}</p>}
<form onSubmit={this.onFormSubmit}>
<input
onChange={this.onInputChange}
value={this.state.description}
name="description"
type="text"
placeholder="Description"
autoFocus
/>
<input
onChange={this.onInputChange}
value={this.state.amount}
name="amount"
type="text"
placeholder="Amount" />
<SingleDatePicker
date={this.state.createdAt}
onDateChange={this.onDateChange}
focused={this.state.calendarFocused}
onFocusChange={this.onFocusChange}
numberOfMonths={1}
isOutsideRange={() => false }
/>
<textarea
onChange={this.onInputChange}
value={this.state.note}
name="note"
placeholder="Add a note for your expense (optional)"
></textarea>
<button>Add Expense</button>
</form>
</div>
)
}
}
我在两个地方使用这个组件 第一个是在这里
function AddExpensePage({ addExpense, history }) {
const onAddSubmit = (data) => {
addExpense(data);
history.push('/');
};
return (
<div>
<h1>AddExpensePage</h1>
<ExpenseForm
onSubmit={onAddSubmit}
/>
</div>
)
}
第二个就在这里
function EditPage(props) {
const onEditSubmit = () => {
console.log('edit submit')
};
return (
<div>
<h1>Edit Expense Page {props.match.params.id}</h1>
<ExpenseForm
onSumbit={onEditSubmit}
/>
</div>
)
}
在第一种情况下,一切正常,我调用通过道具传递的功能(onAddSubmit)。
在第二个中我得到错误 _this.props.onSubmit不是函数。 当我在console.log中使用ExpenseForm的道具时,我在对象中看到了我转移的函数(onEditSubmit)。但是当我在调用this.props.onSubmit之前创建console.log时,我在控制台中看到 undefined 。 所以我无法理解为什么会这样。
答案 0 :(得分:0)
我认为这只是一个错字:
onSumbit={onEditSubmit}
应该是
onSubmit={onEditSubmit}