如何解决React Native 中条件渲染的问题
我有一张地图,我希望在用户长按某个点时出现一个标记。 我有以下代码:
const [coords,setcoords] = React.useState(getcoord());
const [show,setShow] = React.useState(false);
const setPointCoords = (e) => {
setcoords(e.geometry.coordinates);
setShow(!show);
}
return (
<View style={style.page}>
<MapBoxGL.MapView
style={style.map}
rotateEnabled={false}
styleURL="mapBox://styles/daskalgg/ckp26fbmb34iv18otkav9sj4s"
onLongPress={(e) => {
setPointCoords(e);
}}
>
{
show &&
<MapBoxGL.PointAnnotation
key="marker"
id="point"
draggable={true}
coordinate={coords} />
}
</MapBoxGL.MapView>
{
show &&
<Text>test</Text>
}
</View>
);
我遇到的问题是,虽然调用了 setPointCoords 并且 show 的值发生了变化,但标记从未出现。
我注意到的一些事情:
- 用于测试目的的 Text 元素按预期工作。
- 当 show 的初始值为 true 时,问题就会消失。
解决方法
试试这个
{show ? (
<MapboxGL.PointAnnotation
key="marker"
id="point"
draggable={true}
coordinate={coords}
/> )
: null}
,
我找到了一个解决方案,但它很笨
<MapboxGL.PointAnnotation
key="marker"
id="point"
draggable={true}
onSelected={(e) => {
console.log(e);
}}
coordinate={coords} >
<View
key="marker"
style={{
borderColor: "black",backgroundColor: "red",display: show ? 'flex' : 'none'
}}
>
<Text> This is a Marker </Text>
</View>
</MapboxGL.PointAnnotation>
由于我无法控制 PointAnnotation 本身的样式,所以我显示一个视图并通过“显示”控制它的可见性。我不接受它作为正确答案,但希望有更好的答案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。