如何在webview中加载动态html字符串

Rav*_*ran 6 react-native

我想在异步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);
   });
Run Code Online (Sandbox Code Playgroud)

}

 getDataFromServer(responseJson)
 {
   var a ='ravi';
   var b = 'chennai';
   var commonHtml = `my name is ${a} from ${b}`;
   <WebView source={{html: commonHtml}}/>  // not working
 }
Run Code Online (Sandbox Code Playgroud)

NiF*_*iFi -1

您可以通过延迟渲染WebView直到请求完成来实现这一点:

\n\n
constructor(props) {\n  super(props);\n\n  this.state = {\n    commonHtml = ''\n  };\n}\n\ncomponentDidMount() {\n  getMoviesFromApiAsync();\n}\n\ngetMoviesFromApiAsync() {\n  fetch('*****some url*****')\n  .then((response) => response.json())\n  .then((responseJson) => {\n    // Assuming responseJson.data.nameA and responseJson.data.nameB exist\n    const {\xc2\xa0nameA, nameB }\xc2\xa0= responseJson.data;\n    this.setState({commonHtml: `my name is ${nameA} from ${nameB}`});\n  })\n  .catch((error) => {\n    console.error(error);\n  });\n}\n\nrender() {\n  const commonHtml = {\xc2\xa0this.state };\n\n  return (\n    <View>\n      {commonHtml ?\n        <WebView style={{width: 200, height: 200}} source={{html: commonHtml}} /> :\n        (\n          <View>\n            <Text>Loading</Text>\n          </View>\n        )\n      }\n    </View>\n  );\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

此示例WebView仅当 中存在某些内容时才呈现this.state.commonHtml

\n\n

事实上,如果您不想做任何花哨的事情,甚至不需要三元。你可以简单地做

\n\n
render() {\n  return (\n    <WebView style={{width: 200, height: 200}} source={{html: this.state.commonHtml}} />\n  );\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

setState在更改时导致重新渲染this.state.commonHtml

\n