React Native 中条件渲染的问题

时间:2021-06-03 17:31:36

标签: react-native conditional-rendering

我有一张地图,我希望在用户长按某个点时出现一个标记。 我有以下代码:

    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 的值发生了变化,但标记从未出现。

我注意到的一些事情:

  1. 用于测试目的的 Text 元素按预期工作。
  2. 当 show 的初始值为 true 时,问题就会消失。

2 个答案:

答案 0 :(得分:0)

试试这个

{show ? (
   <MapboxGL.PointAnnotation
     key="marker"
     id="point"
     draggable={true}
     coordinate={coords} 
   /> )
: null}

答案 1 :(得分:0)

我找到了一个解决方案,但它很笨

                <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 本身的样式,所以我显示一个视图并通过“显示”控制它的可见性。我不接受它作为正确答案,但希望有更好的答案。

相关问题