首页 > 解决方案 > 如何将变量传递到 WebView 的 HTML

问题描述

我正在尝试将变量从状态传递到 React Native WebView 的 HTML,但遇到了一些麻烦。

在 WebView 中使用 URI 而不是 HTML 时,我能够使其正常工作:

constructor (props) {
    super(props)
    this.state = {
      foo: props.navigation.getParam('foo', 'NO-FOO')
    }
  }
  render() {
    const url = 'http://example.com/Results.aspx?entry=1&foo=' + this.state.foo + '&css=default'
    return (
      <WebView source={{ uri: url }} />
    );
  }

当我尝试对 HTML 做同样的事情时,如果 BAR 是硬编码的,它就可以工作:

  render() {
    const html = '<html><head></head><body><script type="text/javascript" src="http://example.com/LaunchWidget.js?widget=Posting&css=default&foo=BAR&showheader=1></script></body></html>'
    return (
      <WebView source={{ html: html }} />
    );

但是当我尝试用 HTML 做类似的事情时,WebView 只会呈现一个空白页面:

constructor (props) {
    super(props)
    this.state = {
      foo: props.navigation.getParam('foo', 'NO-FOO')
    }
    console.log('foo: ', this.state.foo); // this works as expected but the URL below does not work unless BAR is hard-coded
  }
  render() {
    const html = '<html><head></head><body><script type="text/javascript" src="http://example.com/LaunchWidget.js?widget=Posting&css=default&foo=' + this.state.foo + '&showheader=1></script></body></html>'
    return (
      <WebView source={{ html: html }} />
    );

注意:本例中的 BAR 是一个 7 位数字

标签: javascriptreact-native

解决方案


推荐阅读