[英]React-native native-base datepicker issue
我想知道您是否可以帮助我解决以下问题。 使用基于本机的日期选择器,我试图操纵默认日期。 从父组件加载时,我将其设置为今天的日期。 然后使用一些逻辑来添加 x 个月。 然后在 state 中更新日期,但它没有映射到日期选择器。 请参见下面的代码:
// Parent state from parent component
state = {
index: 0,
routes: [
{ key: '1', title: 'STEP 1' },
{ key: '2', title: 'STEP 2' },
{ key: '3', title: 'STEP 3' },
{ key: '4', title: 'STEP 4' }
],
purposes: [],
purpose_Of_Examination_Id: 0,
colours: [],
colour_Id: 0,
first_Examination: false,
installed_Correctly: null,
defect_Reason_Id: 0,
defect_Reasons: [],
hasDefects: false,
defect: '',
inspected_At: moment().toDate(),
next_Inspection_Date: moment().toDate()
}
// Child component
constructor(props: any) {
super(props);
this.state = this.props.parentState;
}
async componentDidMount() {
this.bindDates();
}
bindDates() {
var inspected_At = moment().toDate();
var next_Inspection_Date = moment().toDate();
var safe_For_Use = false;
if (this.props.inspection.hasDefects == true) {
next_Inspection_Date = moment().toDate();
safe_For_Use = false;
} else {
next_Inspection_Date = moment(inspected_At).add(this.props.equip.inspection_Interval, 'M').toDate();
safe_For_Use = true;
}
this.setState({inspected_At: inspected_At, next_Inspection_Date: next_Inspection_Date, safe_For_Use: safe_For_Use}, () => {
console.log("NEXT INSPECTION DATE state: " + this.state.next_Inspection_Date);
});
}
// Part of view
<View style={styles.nextInspectionDateContainer}>
<View style={styles.inputContainer}>
<Text style={styles.inputLabel}>Next Inspection Date:</Text>
<DatePicker
locale="en_GB"
defaultDate={this.state.next_Inspection_Date}
formatChosenDate={date => { return moment(date).format('DD/MM/YYYY'); }}
onDateChange={(date) => { this.setState({ next_Inspection_Date: date }) }}
/>
</View>
</View>
这很常见(:
this.setState()
是async
的,因此您需要将 promise 从this.setState()
返回到 function ,这将更新您的DatePicker
而不仅仅是记录它们。 然后你可以调用forceupdate()
来显示你的更新。
如果您使用的是无状态功能组件,那会更好,因为您只需要一个简单的Hook
即可完成上述所有操作。
请记住文档:
通常你应该尽量避免使用 forceUpdate() 并且只从 render() 中的 this.props 和 this.state 中读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.