Shu*_*sht 1 android reactjs react-native react-native-maps
从上面的图像中,我有2个视图,当按下棕色或绿色按钮时可以更改。因此,当默认情况下已选择棕色按钮时,地图中就会有一个标记。当我按下绿色按钮时,我希望删除地图的标记。
所以我尝试的是在按下绿色按钮时设置一个异步变量,并在Map组件中获取该异步变量。
借助Map组件中的异步变量,我将让Map知道隐藏标记。但是问题是如何重新呈现地图组件?
更新的问题
丹的解决方案为我工作。但是现在我有一个小问题。当我this.setState
在下面使用时,componentWillMount
它给了我警告。那么,根据接收到的道具的价值,我还可以使用其他什么方法来显示/隐藏我的标记呢?
if(this.props.isMarkerVisible) {
this.setState({ showDots: true })
}
else {
this.setState({ showDots: false })
}
{ this.state.showDots === true &&
<Marker
ref={(mark) => { this.marker = mark; }}
coordinate={{ latitude, longitude }}
pinColor={colors.primaryColor}
image={require('../../../../assets/circle.png')}
/>
}
{ this.state.showDots === false && null }
Run Code Online (Sandbox Code Playgroud)
您的Map
组件将重新呈现时,它的道具和状态变化
将状态变量添加到您的父组件
this.state = {
isMarkerVisible: false // Set this to your default value
}
Run Code Online (Sandbox Code Playgroud)
现在,添加一个将设置状态变量的函数
onPress = isMarkerVisible => {
this.setState({
isMarkerVisible
});
}
Run Code Online (Sandbox Code Playgroud)
最后,onPress
在按钮上修改您的事件
// Green
<TouchableOpacity
onPress={() => this.onPress(false)}
/>
// Brown
<TouchableOpacity
onPress={() => this.onPress(true)}
/>
Run Code Online (Sandbox Code Playgroud)
修改您的Map
组件,使其接受一个isMarkerVisible
prop,其值为this.state.isMarkerVisible
<Map
...props
isMarkerVisible={this.state.isMarkerVisible}
/>
Run Code Online (Sandbox Code Playgroud)
现在在Map
组件内部,您需要修改渲染逻辑,下面是一些伪代码。您尚未添加任何Map
代码,因此我无法提供具体帮助。
If this.props.isMarkerVisible
Then render the marker
Else do not render the marker
Run Code Online (Sandbox Code Playgroud)
更新以反映问题
您可以在Map
组件中执行以下操作。您不需要修改状态,只需使用传入的道具即可。
renderMarker = (coordinates) => {
const { isMarkerVisible } = this.props;
if(!isMarkerVisible) return null;
return (
<Marker
ref={(mark) => { this.marker = mark; }}
coordinate={{ latitude, longitude }}
pinColor={colors.primaryColor}
image={require('../../../../assets/circle.png')}
/>
)
}
render() {
const coordinates = { latitude: 0, longitude: 0 }
return (
<View>
{ this.renderMarker(coordinates) }
</View>
)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
105 次 |
最近记录: |