React Native 中条件渲染的问题
Problem with conditional rendering in 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 的值发生了变化,但标记从未出现。
我注意到的一些事情:
- 用于测试目的的文本元素按预期工作。
- 当 show 的初始值为真时,问题就消失了。
试试这个
{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 本身的样式,我显示一个视图并通过 'show' 控制它的可见性。我不接受它作为正确答案,但希望有更好的答案。
我有一张地图,我希望在用户长按某个点时出现一个标记。 我有以下代码:
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 的值发生了变化,但标记从未出现。
我注意到的一些事情:
- 用于测试目的的文本元素按预期工作。
- 当 show 的初始值为真时,问题就消失了。
试试这个
{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 本身的样式,我显示一个视图并通过 'show' 控制它的可见性。我不接受它作为正确答案,但希望有更好的答案。