简体   繁体   English

传递日期 object 是反应中的支柱

[英]Passing Date object is prop in react

I'm trying to pass a date object as a prop in react native, and access its methods to render data.我正在尝试将日期 object 作为 react native 的道具传递,并访问其方法来呈现数据。

The prop is passed as following: prop 传递如下:

 <Task
                  text={item["text"]}
                  date={item["date"]}
                  time={item["time"]}
                  reminder={item["reminder"]}
                  completed={item["completed"]}
                />

It is accessed as:它被访问为:

<View>
      <View
        style={[
          styles.item,
          completed
            ? { backgroundColor: "#98CBB4" }
            : { backgroundColor: "#CCC9DC" },
        ]}
      >
        <View style={styles.ciricleTitle}>
          <View style={styles.circular}></View>
          <Text style={styles.itemText}>{text}</Text>
        </View>
        <Text style={styles.itemText}>{console.log(date.date)}</Text>
        {/* <Text style={styles.itemText}>{date.getDay()}</Text> */}
      </View>
      {completed && <View style={styles.line} />}
    </View>

i tried expanding the prop with {...item['date']} but it is not working我尝试用{...item['date']}扩展道具,但它不起作用

We have to convert string to date object, You can use new Date(date).getDay()我们必须将字符串转换为日期 object,您可以使用new Date(date).getDay()

Let's clarify your doubt first.让我们先澄清你的疑问。

  1. sending date which is a string as a prop发送日期,它是一个字符串作为道具
  2. sending date which is an object as a prop发送日期是 object作为道具

So, you have made the mistake here.所以,你在这里犯了错误。 You have sent the date string rather than as the date object and trying to access the properties.您已发送日期字符串而不是日期 object 并尝试访问属性。

<div>
 {
  itemList.map(({ text, date, time, reminder, completed }) => (
   <Task {...{ text, date, time, reminder, completed }} />
  ))
 }
</div>

The date you are passing here undoubtedly is a string(which is item.date )你在这里传递的日期无疑是一个字符串(这是item.date

One way to acheive what you want is, send it as a date object..实现您想要的目标的一种方法是,将其作为日期 object 发送。

<Task
 {...{
  text,
  time,
  reminder,
  completed,
  date: new Date(date)
 }}
/>

So that,以便,

<Text style={styles.itemText}>{date.getDay()}</Text>

would become valid.会变得有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM