我试图在父组件内的特定位置渲染多个组件(基于一些计算)。给我垂直位置的计算看起来是正确的,但组件没有显示在它们应该的位置。我尝试了绝对窗口位置和相对组件位置,但没有成功。
父类如下所示:
const top = 170;
const bottom = 10;
const left = 10;
const right = 10;
const styles = StyleSheet.create({
grid: {
flex: 1,
position: 'absolute',
top: top,
height: Dimensions.get('window').height - top - bottom,
width: Dimensions.get('window').width - left - right,
borderLeftColor: 'black',
borderLeftWidth: 1,
borderBottomColor: 'black',
borderBottomWidth: 1
}
});
const DrawGrid: React.FC<IDrawGrid> = ({ maxDistance, elements }) => {
const [gridSize, setGridSize] = useState<LayoutRectangle>();
return (
<View style={styles.grid} onLayout={(event) => {
setGridSize(event.nativeEvent.layout);
}}>
{elements.map((element, index) => {
return (
<DrawElement element={element} maxDistance={maxDistance} gridSize={gridSize} index={index * 2} />
)
})}
</View>
);
};
渲染所有元素的子组件如下所示:
const top = 170;
const bottom = 20;
const left = 10;
const right = 10;
const styles = StyleSheet.create({
elementContainer: {
borderLeftColor: 'red',
borderLeftWidth: 1,
borderTopColor: 'red',
borderTopWidth: 1,
borderRightColor: 'red',
borderRightWidth: 1,
borderBottomColor: 'red',
borderBottomWidth: 1,
borderRadius: 5,
padding: 2,
position: 'relative',
alignSelf: 'flex-start'
}
});
const getVerticalPosition = (someDistance: number, maxDistance: number, height: number) => {
if (!someDistance || !maxDistance) return { top: 0 };
const topDistance = (1 - (someDistance / maxDistance)) * height;
return { top: topDistance };
};
const DrawElement: React.FC<IDrawElement> = ({ maxDistance, element, gridSize, index }) => {
const styleVertical = getVerticalPosition(someDistance, maxDistance, gridSize.height);
return (
<View key={key} style={[styles.elementContainer, styleVertical]}>
<Text>top: {styleVertical.top.toFixed(2)}</Text>
</View>
);
};
我可以看到 getVerticalPosition
如何返回正确的值,但元素永远不会位于预期的位置。在下面的快照中,我打印了每个元素的最高值,我们可以看到它根本没有得到尊重。 (水平位置不在问题范围内)
我的第一个想法是我以某种方式弄乱了样式,我还尝试为每个元素提供不同的 zindex
但没有运气。任何想法会发生什么?任何帮助将不胜感激,谢谢!
最佳答案
我想你不明白布局类型在 React Native 中是如何工作的。这是一个链接:https://reactnative.dev/docs/flexbox#absolute--relative-layout .主要问题是每个与其初始位置相关的子元素的相对
位置。
默认情况下,React Native 中所有元素的position
都等于relative
,因此您无需将其放在样式定义中。
为了更好地理解relative
position scheme,我建议你分两步考虑它的渲染过程:
- 渲染没有任何
top, left, bottom, right
属性的 child ; - 根据当前位置的
top, left, bottom, right
属性移动 child ;
假设您有这样的代码:
<View style={styles.parent}>
<View style={styles.firstChild}/>
<View style={styles.secondChild}/>
</View>
const styles = StyleSheet.create({
parent: {
top: 100,
flex: 1,
},
firstChild: {
top: 100,
height: 50,
},
secondChild: {
top: 80,
height: 70,
},
});
如果我们将上面提到的两个步骤应用于此示例,它将如下所示:
要解决您的问题,您需要对 child 应用绝对
位置方案。只有 absolute
位置方案放置元素,例如 top: 100
属性,相对于其父项的当前顶部向下 100 点。
希望对您有所帮助。
关于javascript - react-native 如何在父组件内的特定位置显示多个组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63067043/