我正在使用 react-timeago 包,我只需要通過道具從父組件獲取資料,當我將資料放入 TimeAgo 的日期道具時,我什么也得不到。
props.date沒有獲取TimeAgo組件中的資料,我嘗試過this.props.date但沒有成功。下面的代碼在同一個組件中
// this returns for ex 'Published 2 days ago'
<div>Published {props.date}</div>
// this returns only 'Published'
<div>Published <TimeAgo date={props.date} formatter={formatter}/></div>
uj5u.com熱心網友回復:
您props.date回傳一個無法直接轉換為日期物件或日期字串的文字字串,首先您需要將其轉換為標準格式,然后將其傳遞給props. 在return塊之前添加此代碼。
var calDate = stringToDate()
function stringToDate(){
let cDate = new Date();
cDate.setDate(cDate.getDate() - parseInt(props.date)); //Get the integer part of X days ago, e.g return the integer 2 from 2 days ago and then subtract 2 days from current date.
//console.log(calDate.toString());
return cDate
}
將傳遞給 prop 的值更新為我們上面計算的值。
// this returns for ex 'Published 2 days ago'
<div>Published {props.date}</div>
// this returns only 'Published'
<div>Published <TimeAgo date={calDate} formatter={formatter}/></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337024.html
標籤:javascript 反应
