我有一个组件,这个组件不过是一个WebView。
我打电话给这个组件,并希望通过诺言返回结果。
我必须确保在加载WebView并在onNavigationStateChange上运行后,我必须返回一个Promise来返回结果。
主要:
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>
);
}
}
ShortUrl:
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
答案 0 :(得分:0)
我无法完全理解您的问题,但似乎您只是在寻找作为prop传递给子组件的函数。诺言完成后,只需调用prop中具有的函数并将其传递给参数,以便在父组件中进行处理即可。
在您的主机中:
[...]
<ShortUrl
ref={r => (this.shortUrl = r)}
style={{ width: 0, height: 0, backgroundColor: '#000' }}
handleResult={ resultArrivingFromChild => { // do what you want with the result }}
/>
在ShortUrl中:
onNavigationStateChange = navState => {
[...] // do what you have to do
this.props.handleResult(resultYouWantToSendBack);
};