[英]Calling Parent Function in Child Component in React
我試圖將一個名為updateTime
的函數從父組件傳遞給子組件。
孩子部件載荷完全正常,但是當handleApply
被調用,它試圖調用this.props.updateTime
但引發錯誤:
this.props.updateTime is not a function
父組件
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
startDate: moment(),
endDate: moment().add(21, 'days'),
minDate: moment(),
};
this.updateTime = this.updateTime.bind(this);
}
updateTime(startDate, endDate) {
this.setState({
startDate: startDate,
endDate:endDate
});
}
render() {
return (
<div>
<DatePicker startDate={this.state.startDate} endDate={this.state.endDate} minDate={this.state.minDate} updateTime={this.props.updateTime}/>
</div>
)
子組件:
class DatePicker extends Component {
constructor(props) {
super(props);
this.handleApply = this.handleApply.bind(this);
}
handleApply(event, picker) {
console.log("updating the time");
this.props.updateTime(picker.startDate, picker.endDate);
}
render() {
const {startDate, endDate, minDate, updateTime} = this.props;
let start = this.props.startDate.format('MMMM Do YYYY h:mm a');
let end = this.props.endDate.format('MMMM Do YYYY h:mm a');
let label = start + ' - ' + end;
let locale = {
format: 'MMMM do YYYY, h:mm:ss a',
separator: ' - ',
applyLabel: 'Apply',
cancelLabel: 'Cancel',
weekLabel: 'W',
customRangeLabel: 'Custom Range',
daysOfWeek: moment.weekdaysMin(),
monthNames: moment.monthsShort(),
firstDay: moment.localeData().firstDayOfWeek(),
};
return (
<div className="form-group">
<div className="date-time-range-picker">
<DatetimeRangePicker
timePicker
timePicker24Hour
showDropdowns
timePickerSeconds
locale={locale}
minDate = {this.props.minDate}
startDate={this.props.startDate}
endDate={this.props.endDate}
onApply={this.handleApply}>
<div className="input-group">
<input type="text" className="form-control" value={label}/>
<span className="input-group-btn">
<Button className="default date-range-toggle">
<i className="fa fa-calendar"/>
</Button>
</span>
</div>
</DatetimeRangePicker>
</div>
<div className="error">{error} </div>
</div>
);
}
您需要從以下位置在父組件中正確引用updateTime
函數:
<DatePicker ... updateTime={this.props.updateTime}/>
至:
<DatePicker ... updateTime={this.updateTime}/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.