flex-direction为row时主动换行

flex-direction为row时主动换行(React native主动换行)

我今天在写react-native时候,遇到了很不舒服的一件事情。因为RN默认是flex布局,所以如果我想要实现inline模式就只能设置父元素的flex-direction的value为row。这样如果我们如果想要换行需要怎么处理呢?

要知道,在RN中是没有<br>标签的,所以要想换行需要采取一些非常的手段。

那有没有什么好办法能够做到主动换行呢?

在正式开始之前我先上一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const arr = [1, 2, 3, 4, 5, 6];

export default function App() {
return (
<SafeAreaView style={styles.container}>
<View style={{ flexDirection: 'row' }}>
{arr.map((item, index) => (
<View>
<Text key={index}>{item}</Text>
</View>
))}
</View>
</SafeAreaView>
);
}

很明显,上述的代码会生成一个纵向排列的123456,如果我们希望在每三个断一下,即将纵向的123456改成横向的123 <br> 456应该如何做呢?

刚开始的时候我问了ChatGPT,他给出的答案是使用伪类撑开元素:

1
2
3
4
5
6
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item break-after">2</div> <!-- 想要在这个元素后换行 -->
<div class="flex-item">3</div>
<div class="flex-item">4</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.flex-container {
display: flex;
flex-wrap: wrap;
flex-direction: row;
}

.flex-item {
width: 100px;
margin: 5px;
}

.break-after::after {
content: "";
flex-basis: 100%;
}

经过我的尝试,这种方法很遗憾的不起任何作用,而且在RN中使用CSS class并不是很容易。但是他给出的代码确实给了我一些启发,经过一些摸索,我发现如果一次渲染两个元素,其中一个是正常元素而另一个负责撑开元素,那么就可以实现换行,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const arr = [1, 2, 3, 4, 5, 6];

export default function App() {
return (
<SafeAreaView style={styles.container}>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', width: 200 }}>
{arr.map((item, index) => {
if (item % 3 !== 0) {
return <Text key={index}>{item}</Text>;
} else {
return (
<>
{[
<Text key={index}>{item}</Text>,
<View style={{ width: '100%' }}></View>,
]}
</>
);
}
})}
</View>
</SafeAreaView>
);
}

但是很抱歉,这样依旧有缺陷,因为reactNative中<></>实际上会影响继承,即Text和View将会被看作一个整体,而不会被解析成两个单独的元素,并且return中的jsx fragment必须有一个根节点,也就说说这种方法与顶上charGPT给出的方法并没有区别,都无法将一个元素完美换行。这只会让我们需要换行的元素变为单独的一行而已。

那么,还有什么方法呢?

完美的换行

这时候我们或许需要更新一下思路,如果在渲染过程中无法做到完美的换行,那么我们为什么不能在数据上动一点手脚呢?经过一系列思路的转换,我突然想到我们完全可以进行一个数组分割+元素嵌套的方式实现换行,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const arr = [1, 2, 3, 4, 5, 6];
export default function App() {
const [arrState, setArrState] = useState([]);
useEffect(() => {
const result = [];
let tempArr = [];
arr.forEach((item) => {
tempArr.push(item);
if (item % 3 === 0) {
result.push(tempArr);
tempArr = [];
}
});
setArrState(result);
}, []);
return (
<SafeAreaView style={styles.container}>
{arrState.map((subArr, index) => (
<View
key={index}
style={{ flexDirection: 'row', flexWrap: 'wrap', width: 200 }}>
{subArr.map((item, subIndex) => {
return <Text key={subIndex}>{item}</Text>;
})}
</View>
))}
</SafeAreaView>
);
}

终于,我们实现了完美的换行!

so,如果你也想要在flex布局中尝试主动换行,那么希望这篇文章能够解答你的疑惑。

当然,如果你有更好的方法,非常希望能在下方评论区和我分享你的好主意🤗


flex-direction为row时主动换行
2023/12/18/technology/css/flex_active_warp/
作者
charlesix59
发布于
2023年12月18日
许可协议