代码之家  ›  专栏  ›  技术社区  ›  Paul

react native component函数promise返回导航状态更改的url

  •  0
  • Paul  · 技术社区  · 7 年前

    我有一个组件,这个组件只是一个webview。

    我打电话给这个组件,我希望通过承诺得到一个结果。

    我必须确保在加载webview并运行onNavigationStateChange之后,我必须返回一个返回结果的承诺。

    主营:

    import * as React from 'react';
    import { View } from 'react-native';
    import ShortUrl from './ShortUrl';
    
    export default class App extends React.Component {
      componentDidMount() {
        this.shortUrl
          .init('https://www.cineblog.life/?trdownload=0&trid=24045&movie=0')
          .then(uid => {
            console.log('URL: ' + uid);
          })
          .catch(err => alert('error: ' + err));
      }
    
      render() {
        return (
          <View>
            <ShortUrl
              ref={r => (this.shortUrl = r)}
              style={{ width: 0, height: 0, backgroundColor: '#000' }}
            />
          </View>
        );
      }
    }
    

    肖特尔:

    import * as React from 'react';
    import { View, WebView } from 'react-native';
    
    export default class ShortUrl extends React.Component {
      constructor() {
        super();
        this.state = {
          initialUrl: '',
          init: false,
          //promise:
        };
      }
    
      init(initialUrl) {
        this.setState({ initialUrl, init: true });
        return new Promise(async (resolve, reject) => {
          resolve('OK');
        });
      }
    
      onNavigationStateChange = navState => {
        const { initialUrl } = this.state;
        if (initialUrl !== navState.url) {
          return new Promise(async (resolve, reject) => {
            resolve(navState.url);
          });
        }
      };
    
      render() {
        const { initialUrl, init } = this.state;
        if (!init) return null;
        return (
          <View>
            <WebView
              source={{
                uri: initialUrl,
              }}
              onNavigationStateChange={this.onNavigationStateChange}
              style={{ flex: 1 }}
            />
          </View>
        );
      }
    }
    

    链接博览会: Here

    1 回复  |  直到 7 年前
        1
  •  0
  •   Milore    7 年前

    我不能完全理解您的问题,但似乎您只是在寻找一个作为道具传递给子组件的函数。一旦您的承诺完成,只需调用prop中的函数并传递一个参数,以便在父组件中处理它。

    主要是:

    [...]
      <ShortUrl
        ref={r => (this.shortUrl = r)}
        style={{ width: 0, height: 0, backgroundColor: '#000' }}
        handleResult={ resultArrivingFromChild => { // do what you want with the result }}
      />
    

    在短途旅行中:

    onNavigationStateChange = navState => {
      [...] // do what you have to do
      this.props.handleResult(resultYouWantToSendBack);
    };