react-native-webview 导航到 URL 列表?
react-native-webview Navigate to a list of URLs?
正如问题标题所说,我正在尝试使用 React Natives WebView 组件导航到 url 的列表。以下是我尝试实现此目的的方法:
export default function App() {
const webViewScript = `
let urls = ["http://example1.com", "http://example2.com", "http://example3.com"];
urls.forEach((url) => {
window.location = url;
window.ReactNativeWebView.postMessage(document.documentElement.innerHTML);
});
true; // note: this is required, or you'll sometimes get silent failures
`;
return (
<WebView
source={{ uri: navUri }}
onMessage={(event) => {
// do something with `event.nativeEvent.data`
alert(event.nativeEvent.data);
}}
injectedJavaScript={webViewScript}
/>
);
}
但是,注入的 javascript 中的 foreach 循环不会阻塞,因此 example3.com 是唯一实际加载的 url。我考虑过在 localStorage 中保留一个计数器变量并使用它来索引数组,在每次页面加载后递增,然后再重定向到下一个 URL (因为局部变量会在页面更改时丢失其状态)。但我觉得可能有更好的方法来完成我正在努力实现的目标,因此我正在与其他人联系以征求您的宝贵意见。
如果您的目标是导航到 URL 列表,那么我认为您的方法可能会使它变得有点复杂。
Web 视图具有回调属性“onLoadEnd”,用于在网站加载时触发下一个导航。
此外,您不需要在 localStorage 中存储变量,reacts useState 非常适合这个。
const urls = [
'https://github.com/react-native-webview/react-native-webview',
'https://whosebug.com/',
'https://expo.dev/',
];
export default function App() {
const [activeIndex, setActiveIndex] = useState(0);
return (
<WebView
style={styles.container}
source={{ uri: urls[activeIndex] }}
onLoadEnd={() => {
if (activeIndex + 1 === urls.length) return;
setActiveIndex(activeIndex + 1);
}}
/>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: Constants.statusBarHeight,
},
});
正如问题标题所说,我正在尝试使用 React Natives WebView 组件导航到 url 的列表。以下是我尝试实现此目的的方法:
export default function App() {
const webViewScript = `
let urls = ["http://example1.com", "http://example2.com", "http://example3.com"];
urls.forEach((url) => {
window.location = url;
window.ReactNativeWebView.postMessage(document.documentElement.innerHTML);
});
true; // note: this is required, or you'll sometimes get silent failures
`;
return (
<WebView
source={{ uri: navUri }}
onMessage={(event) => {
// do something with `event.nativeEvent.data`
alert(event.nativeEvent.data);
}}
injectedJavaScript={webViewScript}
/>
);
}
但是,注入的 javascript 中的 foreach 循环不会阻塞,因此 example3.com 是唯一实际加载的 url。我考虑过在 localStorage 中保留一个计数器变量并使用它来索引数组,在每次页面加载后递增,然后再重定向到下一个 URL (因为局部变量会在页面更改时丢失其状态)。但我觉得可能有更好的方法来完成我正在努力实现的目标,因此我正在与其他人联系以征求您的宝贵意见。
如果您的目标是导航到 URL 列表,那么我认为您的方法可能会使它变得有点复杂。
Web 视图具有回调属性“onLoadEnd”,用于在网站加载时触发下一个导航。
此外,您不需要在 localStorage 中存储变量,reacts useState 非常适合这个。
const urls = [
'https://github.com/react-native-webview/react-native-webview',
'https://whosebug.com/',
'https://expo.dev/',
];
export default function App() {
const [activeIndex, setActiveIndex] = useState(0);
return (
<WebView
style={styles.container}
source={{ uri: urls[activeIndex] }}
onLoadEnd={() => {
if (activeIndex + 1 === urls.length) return;
setActiveIndex(activeIndex + 1);
}}
/>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: Constants.statusBarHeight,
},
});