在使用reactNative按下按钮后打开WebView

时间:2017-10-28 17:31:30

标签: react-native webview

我正在使用React Native开发移动应用程序。我想在按下按钮后打开WebView。这是我的代码,但它不起作用。 onPress方法按钮不起作用。

import React, { Component } from 'react';
import { View, StyleSheet, Button, WebView } from 'react-native';
import { Constants } from 'expo';


export default class webView extends Component {

  onNavigationStateChange = navState => {
   if (navState.url.indexOf('https://www.google.com') === 0) {
   const regex = /#access_token=(.+)/;
   const accessToken = navState.url.match(regex)[1];
   console.log(accessToken);
 }
};

renderContent() {
 return (
   <WebView
     source={{
       uri: '',
    }}
     onNavigationStateChange={this.onNavigationStateChange}
     startInLoadingState
     scalesPageToFit
     javaScriptEnabled
     style={{ flex: 1 }}
   />
 );
}

render() {
 return (
   <View style={styles.container}>
     <Button
       style={styles.paragraph}
       title="Login"
       onPress={() => this.renderContent()}
     />
   </View>
 );
}
}

const styles = StyleSheet.create({
 container: {
   flex: 1,
   alignItems: 'center',
   justifyContent: 'center',
   paddingTop: Constants.statusBarHeight,
   backgroundColor: '#ecf0f1',
 },
});

我也试过onPress={this.renderContent()},但它给了一个例外。我能做什么 ?

2 个答案:

答案 0 :(得分:2)

您无法在Component的render()方法中呈现WebView。只需将render视为您网页的DOM即可。您需要在渲染组件中为组件提供一个位置,而不是删除它或添加它,请参阅我从renderContent方法调用render。因此,只要状态变量showWebView为真,它就会呈现WebView你应该这样做:

import React, { Component } from 'react';
import { View, StyleSheet, Button, WebView } from 'react-native';
import { Constants } from 'expo';


export default class webView extends Component {

state={
  showWebView: false
}

onNavigationStateChange = navState => {
   if (navState.url.indexOf('https://www.google.com') === 0) {
   const regex = /#access_token=(.+)/;
   const accessToken = navState.url.match(regex)[1];
   console.log(accessToken);
 }
};

renderContent() {
 return (
   <WebView
     source={{
       uri: '',
    }}
     onNavigationStateChange={this.onNavigationStateChange}
     startInLoadingState
     scalesPageToFit
     javaScriptEnabled
     style={{ flex: 1 }}
   />
 );
}

render() {
 return (
   <View style={styles.container}>
     { this.state.showWebView && this.renderContent() }
     <Button
       style={styles.paragraph}
       title="Login"
       onPress={() => this.setState({showWebView: true})}
     />
   </View>
 );
}
}

const styles = StyleSheet.create({
 container: {
   flex: 1,
   alignItems: 'center',
   justifyContent: 'center',
   paddingTop: Constants.statusBarHeight,
   backgroundColor: '#ecf0f1',
 },
});

答案 1 :(得分:0)

我认为您必须导入以下内容

import { WebView } from 'react-native-webview' 

代替

'react'