我试图将状态中的变量传递到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位数字