【问题标题】:How to break line or wrap content inside ScrollView depending on a condition如何根据条件在 ScrollView 中换行或包装内容
【发布时间】:2020-08-21 17:11:18
【问题描述】:

我想在第一张图片中实现类似的效果,如果条件为真,视图将放置在同一行,如果不是,则下一个视图必须放置在下一行。

在我的应用程序中,我现在有这个结果:

代码:

<ScrollView contentContainerStyle={styles.exercisesContainer}>
            {item.category_workouts.map((exercice, index) => (
              <Exercises
                key={index}
                img={AssetsManager.Images.exerciseImg}
                title={exercice.workout_name}
                level={exercice.level}
              />
            ))}

//
//
 exercisesContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
  },

【问题讨论】:

  • 你希望你的结果是什么。我认为您在这里所拥有的没有任何问题,这是我所期望的。您打算使用什么样的条件来确定一个项目是否在自己的行上?您的问题缺少许多重要信息。
  • 条件与练习的级别有关,如果两个视图代表两个相同级别的练习,则将它们放在同一行,否则必须下一个。
  • 这对我来说没有多大意义,也许如果你向我们展示了你希望你给定的例子看起来更有意义的东西。
  • 抱歉让您感到困惑,我希望我的应用(带有锻炼)看起来像第一个带有循环的图像...

标签: react-native flexbox


【解决方案1】:

找到了我的问题的解决方案。使用一个函数,我根据他的 prop level 计算每个元素的 with。 例子:

  • 如果第一个元素的级别是“初学者”,而下一个元素的级别是“中”,则第一个元素将采用“100%”宽度,从而占据孔线,因为他是唯一的“初学者”元素。
  • 如果我们有三个具有相同级别的元素可能是“高级”,它们将分别被赋予“33%”的宽度。

这是我的函数,但是它需要一些重构:

const getExercicesWidth = exercices => {
    const exercicesLevels = [];
    exercices.forEach(exercice => {
      exercicesLevels.push(exercice.level);
    });
    let widthArray = [];
    let counter = 1;
    for (let i = 0; i < exercicesLevels.length; i++) {
      if (i === 0) {
        continue;
      }
      if (exercicesLevels[i] == exercicesLevels[i - 1]) {
        counter++;
      } else {
        widthArray.push(counter);
        counter = 1;
      }
    }
    widthArray.push(counter);
    const percentageWidthArray = [];
    widthArray.forEach(number => {
      let c = number;
      while (c > 0) {
        percentageWidthArray.push(`${Math.round(100 / number)}%`);
        c--;
      }
    });
    return percentageWidthArray;
  };

现在的结果是这样的:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    相关资源
    最近更新 更多