首页 > 解决方案 > 点击更改谷歌地图的主题 - React Native

问题描述

我已经反应原生地图,我将自定义地图主题设置为this.state.mapTheme.

constructor() {
    super();
    this.state = {
        mapTheme: Themes.SANANDREAS
    }
}

我有这样的渲染方法:

render() {
    return (
        <Container style ={styles.container}>      
            <Button rounded style={styles.contributeButton} onPress={() => {
                this.setState({
                    mapTheme: Themes.BROWNTHEME
                })
            }} iconLeft light>
              <Icon name='hand' />
              <Text>Contribute</Text>
            </Button>
            <MapView
                style={styles.map}
                provider = { MapView.PROVIDER_GOOGLE }
                customMapStyle = { this.state.mapTheme }
            ></MapView>
        </Container>
);}

这一切似乎都在工作,但是当我改变按下按钮的状态时,渲染方法被调用但主题没有改变。我的两个主题都有效,但在媒体上没有任何反应。页面重新加载,但没有使用新主题。我在这里做错了什么?

标签: javascriptreact-native

解决方案


考虑到MapView组件的生命周期功能,如果传递了新的样式道具,它不会自动更新样式。_updateStyle你应该通过在'ref'的帮助下直接调用主题更改来强制它:

setMapRef = ref => this.mapRef = ref;

handleButtonClick = () => {
  this.setState({ mapTheme: Themes.BROWNTHEME }, () => {
    this.mapRef._updateStyle();
  })
}

render() {
  return (
     <Container>      
       <Button onPress={this.handleButtonClick}
         title="Update map theme"
       />
       <MapView
         ref={this.setMapRef}
         customMapStyle={this.state.mapTheme}
       />
     </Container>
  );
}

推荐阅读