代码之家  ›  专栏  ›  技术社区  ›  Farzan Najipour

ReactJs-条件映射

  •  0
  • Farzan Najipour  · 技术社区  · 6 年前

    我决定用一个按钮来显示/隐藏地图。这是我的代码:

    let showingMap = true;
    const toggleMapVisibility = () => {
        showingMap = !showingMap;
        console.log(showingMap);
    };
    
    const DetailModal = (props) => (
      <Button onClick={toggleMapVisibility}>Hide/Show</Button>
                  {
                  showingMap ?
                      <Segment>
                          <MapObject
                              isMarkerShown
                              lat={props.order.user.userAddressPoint.lat}
                              lng={props.order.user.userAddressPoint.lng}
                              googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
                              loadingElement={<div style={{ height: `100%` }} />}
                              containerElement={<div style={{ height: `400px` }} />}
                              mapElement={<div style={{ height: `100%` }} />}
                          />
                      </Segment> :
                      null
                }
    }
    

    嗯,地图显示的是初始状态。然而,当我点击按钮时 showingMap 变量false,但它不能隐藏映射。我没有错。

    有什么建议吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Vibhanshu Shiljo Paulson    6 年前

    您需要更改状态或道具以重新提交react组件。

    在这里,您可以在DetailModal组件中添加本地状态。

    class DetailModal extends React.Component {
    
    
      state = {
        showingMap: true,
      }
    
      toggleMapVisibility = () => {
       this.setState((prevState) => (
         {
           showingMap: !prevState.showingMap
         }
       ))
      };
    
      render() {
        const { showingMap } = this.state; 
        const { order } = this.props;
        return (
          <React.Fragment>
            <Button onClick={this.toggleMapVisibility}>Hide/Show</Button>
            {
              showingMap ?
                <Segment>
                  <MapObject
                    isMarkerShown
                    lat={order.user.userAddressPoint.lat}
                    lng={order.user.userAddressPoint.lng}
                    googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
                    loadingElement={<div style={{ height: `100%` }} />}
                    containerElement={<div style={{ height: `400px` }} />}
                    mapElement={<div style={{ height: `100%` }} />}
                  />
                </Segment> :
                null
            }
          </React.Fragment>
        )
      }
    }
    
        2
  •  1
  •   Snaz    6 年前

    将showingMap置于state和toggleMapVisibility调用中

    this.setState({ showingMap: !this.state.showingMap)};