You need to enable JavaScript to run this app. React Native使用DateTimePicker报TypeError: date is not a function求助
优惠活动
大模型
产品
解决方案
定价
更多

React Native使用DateTimePicker报TypeError: date is not a function求助

错误根源定位
  • 变量名遮蔽+书写错误:给DateTimePicker绑定的onChange匿名回调,将回调入参命名为date,这个入参本质是组件返回的选中日期对象;本意是想调用状态更新方法setDate更新选中值,但是漏写了方法名里的set前缀,直接写成了date(new Date(date)),相当于把拿到的日期对象当函数调用,直接触发TypeError。
  • 未使用正确的API对接逻辑:已经在组件外写好了符合DateTimePicker规范的onChange处理函数,但绑定组件时没有复用,反而编写了不符合组件API的自定义回调。
  • 无效属性冗余:onChangeText是文本输入类组件的专属属性,DateTimePicker不存在该属性,传入后不会生效,属于无意义的冗余代码。
具体修复步骤
  • 移除自定义的错误匿名onChange逻辑,直接绑定已经写好的符合API规范的onChange处理函数,注意DateTimePicker的回调签名是(event, selectedDate) => void,第一个参数为事件对象,第二个参数才是用户选中的日期值。
  • 移除DateTimePicker上不存在的onChangeText属性,如果需要同步更新生日相关字段,直接在已有的onChange回调中,拿到选中的日期值后执行对应的状态更新即可。
  • 注意命名规范:避免回调形参和外层状态变量、状态更新方法重名,减少变量遮蔽带来的逻辑错误。
修复后的代码示例
// 原有状态定义保持不变
const [date, setDate] = useState(new Date(1598051730000));
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);

// 修正后的onChange逻辑,补充需要的生日字段同步
const onChange = (event, selectedDate) => {
  const currentDate = selectedDate || date;
  setShow(Platform.OS === 'ios');
  setDate(currentDate);
  // 同步更新生日字段,替代原本无效的onChangeText属性
  set_birthdate(currentDate);
};

const showMode = (currentMode) => {
  setShow(true);
  setMode(currentMode);
};

const showDatepicker = () => {
  showMode('date');
};

// 修正后的DateTimePicker组件
<DateTimePicker
  testID="dateTimePicker"
  display="default"
  mode={mode}
  value={date}
  onChange={onChange}
/>

内容的提问来源于stack exchange,提问作者Faridz Kurnia Chandra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.31 20:57:03