如何在react native中自动执行按钮?

n6lpvg4x  于 6个月前  发布在  React
关注(0)|答案(1)|浏览(73)

我在react native中编码,我希望当用户在我的应用程序上时自动单击按钮并执行函数。我希望当用户打开我的应用程序时,Web浏览器自动打开。到目前为止,我的代码是:

import React, { useState } from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import Constants from 'expo-constants';

export default function App() {
  const [result, setResult] = useState(null);
  
  const _handlePressButtonAsync = async () => {
    let result = await WebBrowser.openBrowserAsync('https://vitech-104517.square.site/');
    setResult(result);
  };
  return (
    <View style={styles.container}>
      <Button title="Open WebBrowser" onPress={_handlePressButtonAsync} />
      <Text>{result && JSON.stringify(result)}</Text>
      
    </View>
  );
}

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

字符串
每次用户使用我的应用时,“打开Web浏览器”按钮都需要自动执行。我想通过调用react native中的函数来执行此操作。如何才能做到这一点?

fwzugrvs

fwzugrvs1#

试试这个:

// Note the additional import of useEffect
import React, { useState, useEffect } from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import Constants from 'expo-constants';

export default function App() {
  const [result, setResult] = useState(null);

  useEffect(() => {
    _handlePressButtonAsync();
    // by adding the empty brackets below this code will only run once
  }, []);
  
  const _handlePressButtonAsync = async () => {
    let result = await WebBrowser.openBrowserAsync('https://vitech-104517.square.site/');
    setResult(result);
  };
  return (
    <View style={styles.container}>
      <Button title="Open WebBrowser" onPress={_handlePressButtonAsync} />
      <Text>{result && JSON.stringify(result)}</Text>
      
    </View>
  );
}

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

字符串

相关问题