[英]Use multiple lines javascript in React
I have this source code, in React
function component我有这个源代码,在React
function 组件中
return (
result.map(item => (
<tr key={item.id}>
<td>
{new Date(item.pub_date).getFullYear()} /
{new Date(item.pub_date).getMonth()} /
{new Date(item.pub_date).getDate()}
</td>
</tr>
However in this script, it require three Date
instances.但是在这个脚本中,它需要三个Date
实例。
I want to shorten like this.我想像这样缩短。
var date = new Date(item.pub_date)
date.getFullYear() / date.getMonth() /date.getDate()
Is it correct idea?这是正确的想法吗? or is it impossible to this in JSX??还是在 JSX 中不可能做到这一点?
You can achieve what you want with a little different way with the use of template literals and setting date variable outside of the return scope.您可以通过使用模板文字和在返回 scope 之外设置日期变量以稍微不同的方式实现您想要的。
return (
result.map(item => {
const date = new Date(item.pub_date)
return (
<tr key={item.id}>
<td>
{`${date.getFullYear()} / ${date.getMonth()} / ${date.getDate()}`}
</td>
</tr>
)
})
)
You can create a seperate function for formatting date:您可以创建一个单独的 function 用于格式化日期:
function getDate(dateValue){
let date = new Date(dateValue);
return `${date.getFullYear()} / ${date.getMonth()} / ${date.getDate()}`
}
return (
result.map(item => {
return (
<tr key={item.id}>
<td>
{getDate(item.pub_date)}
</td>
</tr>
)
})
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.