Gur*_*ran 5 javascript react-native
我正在尝试为我的应用程序在React-Native中创建一个菜单,该菜单应通过以下方式具有多个图标

图标应在同一行并包装,这样,如果屏幕更大,则更多图标将在同一行。
我当前的代码如下
import React from 'react';
import { StyleSheet, View } from 'react-native';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={styles.box}></View>
<View style={styles.box}></View>
<View style={styles.box}></View>
<View style={styles.box}></View>
<View style={styles.box}></View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'space-evenly',
flexDirection: 'row',
flexWrap: 'wrap',
paddingTop: 40
},
box: {
width: 100,
height: 100,
backgroundColor: 'aqua',
margin: 10,
}
});
Run Code Online (Sandbox Code Playgroud)
当前输出如下
将来孩子的数量可能会发生变化,但我需要在两侧留出一定的间距,使用flex-start会给出以下输出,这是错误的。我也希望在两侧也留出一定的间距。
我如何将其向左对齐,并使物品周围的空间与上面的图像一样均匀?
我采取了不同的方法,使用另一个视图作为包装器并计算其宽度,这样更容易确定列宽度。唯一的问题是我们应该知道项目的宽度,这对我来说不会成为问题。代码如下。
import React from 'react';
import { StyleSheet, View, ScrollView } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
width: 110
};
}
render() {
//width of child is 110
const width = `${100 / parseInt(this.state.width / 110)}%`;
return (
<ScrollView>
<View style={styles.container} onLayout={this.onLayout.bind(this)}>
<View style={[styles.wrapper, { width: width }]}>
<View style={styles.box}></View>
</View>
<View style={[styles.wrapper, { width: width }]}>
<View style={styles.box}></View>
</View>
<View style={[styles.wrapper, { width: width }]}>
<View style={styles.box}></View>
</View>
<View style={[styles.wrapper, { width: width }]}>
<View style={styles.box}></View>
</View>
<View style={[styles.wrapper, { width: width }]}>
<View style={styles.box}></View>
</View>
</View>
</ScrollView>
);
}
onLayout(e) {
if (this.state.width !== e.nativeEvent.layout.width) {
this.setState({
width: e.nativeEvent.layout.width
})
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'flex-start',
justifyContent: 'flex-start',
flexDirection: 'row',
flexWrap: 'wrap',
paddingTop: 40
},
box: {
width: 100,
height: 100,
backgroundColor: 'green',
},
wrapper: {
marginVertical: 10, alignItems: 'center'
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
239 次 |
| 最近记录: |