如何在react native中单击按钮或自动运行函数?

vu8f3i0k  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(136)

我在react native中编码,我想打开我的按钮,它会转到我代码中指定的网站。我想通过按按钮或运行我的功能自动打开网站。我尝试在react native中使用useEffect,但它不起作用。有人可以告诉我如何做到这一点吗?
到目前为止,我的代码是:

// Note the additional import of useEffect
import React, { useState, useEffect,  useRef  } from 'react';
import { TouchableOpacity, 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',
  },
});

字符串

rjee0c15

rjee0c151#

你可以useEffect,试试这样

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

  useEffect(() => {
    _handlePressButtonAsync();
  }, []);

  const _handlePressButtonAsync = async () => {
    let result = await WebBrowser.openBrowserAsync('https://vitech-104517.square.site/');
    setResult(result);
  };

  return (
    <View style={styles.container}>
      <Text>Website will open automatically</Text>
      <Text>{result && JSON.stringify(result)}</Text>
    </View>
  );
}

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

字符串

相关问题