正如问题标题所说,我正在尝试使用React Natives组件导航到urls列表。以下是我尝试实现这一点的方法:
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之前递增(因为局部变量将在页面更改时丢失其状态)。但我觉得可能有更好的方法来实现我正在努力实现的目标,所以我正在与其他人联系,以便获得你们的宝贵意见。
发布于 2021-09-01 14:47:29
如果你的目标是导航到一个urls列表,那么我认为你的方法可能会让它变得有点复杂。
webview有回调prop‘onLoadEnd’,当一个站点加载后,你可以用它来触发下一次导航。
此外,您不需要在localStorage中存储变量,reacts非常适合这一点。
const urls = [
'https://github.com/react-native-webview/react-native-webview',
'https://stackoverflow.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,
},
});https://stackoverflow.com/questions/69003895
复制相似问题