You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript/React中如何从JSX元素获取格式化后的日期值

如何取出目标日期值
  • 你写的 <prettyDate value={new Date()} /> 是无子女的JSX元素,test.props.children 本身就是 undefined,给 prettyDate 传这个值自然会触发解构报错——它没法从undefined里拿到value属性。
  • 正确的取值方式分两种情况:
    1. 直接用现有函数的输出:既然调用 prettyDate(test.props) 能得到预期的日期字符串,直接用这个返回值就行:
      const targetDate = prettyDate(test.props);
      console.log(targetDate); // 输出 "2022/09/16 12:51" 这类格式
      
    2. 手动格式化原始Date对象:如果需要自己处理日期,先从props里取出原始的Date实例,再格式化为目标格式:
      // 取出原始日期对象
      const rawDate = test.props.value;
      // 自定义格式化函数
      function formatToTarget(date) {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        const h = String(date.getHours()).padStart(2, '0');
        const min = String(date.getMinutes()).padStart(2, '0');
        return `${y}/${m}/${d} ${h}:${min}`;
      }
      // 得到目标日期字符串
      const targetDate = formatToTarget(rawDate);
      console.log(targetDate);
      

内容的提问来源于stack exchange,提问作者Katharina Schreiber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:10:35