You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native WebView 底部购物篮按钮未登录隐藏登录后启用实现方法

要实现登录态控制底部购物篮按钮的显隐/可用状态,你可以通过「RN端维护登录状态 + WebView与RN双向通信」的方案实现,具体修改如下:
你当前的按钮实现效果参考:
按钮实现效果


步骤1:新增登录状态字段

在组件的state初始化位置添加登录状态标记,默认值为false代表未登录:

// 示例(放在你的constructor或者state定义位置)
state = {
  // 保留原有字段:url、active、clicked等
  isLoggedIn: false // 新增登录状态字段
}

步骤2:给WebView添加消息监听

给WebView组件新增onMessage属性,用来接收H5页面发送的登录状态变更通知,同步更新RN端的登录状态:

<WebView 
  source={{uri:this.state.url}} 
  ref={WEBVIEW_REF} 
  useWebKit={true} 
  cacheEnabled={true} 
  style={{marginTop: 30, flex: 1}}
  onLoadProgress={({ nativeEvent }) => {this.loadingProgress = nativeEvent.progress;}}
  {/* 新增消息监听逻辑 */}
  onMessage={({nativeEvent}) => {
    const eventData = JSON.parse(nativeEvent.data)
    // 收到登录成功通知
    if(eventData.type === 'LOGIN_SUCCESS') {
      this.setState({isLoggedIn: true})
    }
    // 可选:收到登出通知时隐藏购物篮
    if(eventData.type === 'LOGOUT') {
      this.setState({isLoggedIn: false})
    }
  }}
/>

步骤3:修改H5侧登录逻辑

在H5的登录接口请求成功的回调函数中,新增代码给RN端发送登录成功通知:

// H5侧代码(放在登录成功回调里)
if(window.ReactNativeWebView) {
  window.ReactNativeWebView.postMessage(JSON.stringify({
    type: 'LOGIN_SUCCESS'
  }))
}
// 同理登出成功时发送type为LOGOUT的消息即可

步骤4:控制购物篮按钮的显隐/可用状态

修改底部Footer部分的按钮渲染逻辑:

  • 若要完全隐藏购物篮:用条件判断控制按钮渲染
<Footer>
  <FooterTab>
    <Button vertical onPress={() => this.onPressButtonURL(this.site_url+'index.php')} danger={this.state.clicked}><Icon type="FontAwesome" name="home" /><Text></Text></Button>
    {/* 仅登录状态下渲染购物篮按钮 */}
    {this.state.isLoggedIn && (
      <Button vertical onPress={() => this.onPressButtonURL(this.site_url+'sepetimigoster.html')} danger={this.state.clicked}><Icon type="FontAwesome" name="shopping-basket" id="shopping-basket" /><Text></Text></Button>
    )}
    <Button vertical onPress={() => this.onPressButtonURL(this.site_url+'uyegiris.html')}><Icon type="FontAwesome" name="user" /><Text></Text></Button>
    <Button vertical onPress={() =>this.refs[WEBVIEW_REF].goBack()}><Icon type="FontAwesome" name="arrow-left" /><Text></Text></Button>
    <Button vertical onPress={() =>this.refs[WEBVIEW_REF].goForward()}><Icon type="FontAwesome" name="arrow-right" /><Text></Text></Button>
  </FooterTab>
</Footer>
  • 若要置灰不可点击而非隐藏:给按钮绑定disabled={!this.state.isLoggedIn}属性,再自定义置灰状态的样式即可。

如果需要持久化登录状态避免App重启后状态丢失,可以把登录状态存在AsyncStorage中,组件初始化时读取存储值赋值给isLoggedIn即可。


内容的提问来源于stack exchange,提问作者Onur Arik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:36:02