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

React Native触发onPress事件后react-native-webview组件不显示问题求助

问题原因
  • 事件回调返回的JSX不会被渲染:onPress 是用户交互的事件回调函数,该函数内返回的 <WebView/> 组件不会被插入到React的渲染树中,只有组件render方法返回的JSX才会被挂载到界面上,这是WebView不显示的核心原因。
  • 缺少状态控制和渲染占位:没有定义状态控制WebView的显隐,也没有在render方法中预留WebView的渲染位置。
修复方案

按照以下步骤修改即可:

  1. 给组件添加状态变量,用于控制WebView的显示/隐藏
  2. 修改onPress逻辑,点击时修改状态触发组件重渲染,而非直接返回JSX
  3. 在render方法中添加条件渲染逻辑,状态满足时渲染WebView组件

修复后完整代码

import {View, TouchableNativeFeedback} from 'react-native';
import {Text, Card, Divider} from 'react-native-elements';
import moment from 'moment';
import {WebView} from 'react-native-webview';
import React from 'react';

export default class DataItem extends React.Component {
  constructor(props) {
    super(props);
    // 新增WebView显控状态
    this.state = {
      showWebView: false
    };
  }

  render() {
    const {title, description, publishedAt, source, urlToImage, url} = this.props.article;
    const {noteStyle, featuredTitleStyle} = styles;
    const time = moment(publishedAt || moment.now()).fromNow();

    // 状态为真时渲染WebView,flex:1保证WebView占满可用空间
    if (this.state.showWebView) {
      return <WebView source={{uri: url}} style={{flex: 1, marginTop: 20}} />;
    }

    return (
      <TouchableNativeFeedback
        useForeground
        // 点击时修改状态触发重渲染
        onPress={() => this.setState({showWebView: true})}>
        <Card>
          <Text style={{fontWeight: 'bold'}}> {title || 'YEET'} </Text>
          <Divider style={{backgroundColor: '#dfe6e9', margin: 5}} />
          <Card.Image source={{uri: urlToImage}} />
          <Text style={{marginBottom: 10}}>{description || 'Read More..'}</Text>
          <Divider style={{backgroundColor: '#dfe6e9'}} />
          <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
            <Text style={noteStyle}>{source.name.toUpperCase()}</Text>
            <Text style={noteStyle}>{time}</Text>
          </View>
        </Card>
      </TouchableNativeFeedback>
    );
  }
}

const styles = {
  noteStyle: {
    fontSize: 12,
    color: '#636e72'
  },
  featuredTitleStyle: {
    fontSize: 16,
    fontWeight: 'bold'
  }
};
补充说明

如果不需要替换整个卡片显示WebView,而是要在当前卡片下方等位置显示,只需要把WebView和卡片放在同一个父View容器中,通过状态控制display属性显隐即可;如果需要增加返回卡片的功能,只需要添加对应的按钮,点击时将showWebView设置为false即可。

内容的提问来源于stack exchange,提问作者Frank Boccia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 01:27:03