javascript 如何像console.log那样在react-native中显示循环的结果,

c9qzyr3d  于 2022-10-30  发布在  Java
关注(0)|答案(2)|浏览(140)

我遇到了这种情况下的问题。我想打印像console.log在react nativex 1c 0d1x屏幕中所做的那样
`

const dString = text;
  const days = 30;

  let [day, month, year] = dString.split('/');

  // month - 1 as month in the Date constructor is zero indexed
  const now = new Date(year, month - 1, day);
  let loopDay = now;
  for (let i = 0; i <= days; i++) {
    loopDay.setDate(loopDay.getDate() + 6);
    console.log ('Day: ' + loopDay);
  }

这是我的代码,我想在react-native中打印函数的返回,这样循环的结果就可以显示在我的屏幕上了。

pgky5nke

pgky5nke1#

解决方法:

import {View,Text} from 'react-native';

export default function App() {

  const ShowDates = () => {
    const dString = '29/10/2022';
    const days = 30;

    let [day, month, year] = dString.split('/');

    // month - 1 as month in the Date constructor is zero indexed
    const now = new Date(year, month - 1, day);
    let loopDay = now;

    let tempArray = [];

    for (let i = 0; i <= days; i++) {
      loopDay.setDate(loopDay.getDate() + 6);
      tempArray.push(loopDay);
    } 

    return tempArray;
  } 

  return (
    <View style={{flex:1,justifyContent:'center',alignItems:'center',paddingTop:30}}>
    {ShowDates()?.map((item,index)=>(
      <Text key={index}>Day : {item.toLocaleString()} </Text>
    ))}
    </View>
  );
}

Solution Image
希望能有所帮助😊

5ssjco0h

5ssjco0h2#

一种方法是将所有循环天数添加到数组中,如下所示:
要增加日期,可以乘以i以增加偏移量。

const loopDays = [];
const now = new Date(year, month - 1, day);
for (let i = 0; i <= days; i++) {
  const loopDay = new Date(now);
  loopDay.setDate(loopDay.getDate() + 6 * (i + 1));
  console.log("Day: " + loopDay);
  loopDays.push(loopDay);
}

您可以通过在loopDays上循环来显示它们,如下所示

return (
  <View>
    {loopDays.map((day) => {
      return <Text>Day: {day}</Text>;
    })}
  </View>
);

相关问题