react-native – 如何在webview中加载动态html字符串
发布时间:2020-12-15 20:19:45 所属栏目:百科 来源:网络整理
导读:我想在异步Web服务请求完成时在webview中加载动态html字符串.我怎样才能做到这一点? WebView source={{html: dynamichtml}}/ getMoviesFromApiAsync() { return fetch('*****some url*****') .then((response) = response.json()) .then((responseJson) = {
我想在异步Web服务请求完成时在webview中加载动态html字符串.我怎样才能做到这一点?
<WebView source={{html: dynamichtml}}/> getMoviesFromApiAsync() { return fetch('*****some url*****') .then((response) => response.json()) .then((responseJson) => { this.setState({isLoading: false,jsonData: responseJson}); this.getDataFromServer(responseJson); return responseJson; }) .catch((error) => { console.error(error); }); } getDataFromServer(responseJson) { var a ='ravi'; var b = 'chennai'; var commonHtml = `my name is ${a} from ${b}`; <WebView source={{html: commonHtml}}/> // not working } 解决方法
你可以通过例如在请求完成之前延迟WebView的呈现:
constructor(props) { super(props); this.state = { commonHtml = '' }; } componentDidMount() { getMoviesFromApiAsync(); } getMoviesFromApiAsync() { fetch('*****some url*****') .then((response) => response.json()) .then((responseJson) => { // Assuming responseJson.data.nameA and responseJson.data.nameB exist const {?nameA,nameB }?= responseJson.data; this.setState({commonHtml: `my name is ${nameA} from ${nameB}`}); }) .catch((error) => { console.error(error); }); } render() { const commonHtml = {?this.state }; return ( <View> {commonHtml ? <WebView style={{width: 200,height: 200}} source={{html: commonHtml}} /> : ( <View> <Text>Loading</Text> </View> ) } </View> ); } 此示例仅在this.state.commonHtml中存在某些内容时呈现WebView. 事实上,如果你不想做任何奇特的事情,甚至不需要三元.你可以干脆做 render() { return ( <WebView style={{width: 200,height: 200}} source={{html: this.state.commonHtml}} /> ); } 当this.state.commonHtml发生更改时,setState会导致重新呈现. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |