【问题标题】:About injectScript in WebView for React-Native关于 React-Native 的 WebView 中的 injectScript
【发布时间】:2016-12-01 15:01:03
【问题描述】:

WebView 加载网页

我需要在页面中调用React-Native组件方法

class Mwap extends Component {

constructor(props) {
    super(props);
    this.injectScript = `
        function setTitle(title){
            mwap.MyClick();
        }
    `;
}

componentDidMount(){
    window.mwap = this;
}

MyClick(){
    console.log('Call me');
}

render() {
    return (
        <View style={styles.container}>
            <MwapHeader
                goBack={this.goBack.bind(this)}
                closeWebView={this.closeWebView.bind(this)}
                toonShare={this.toonShare.bind(this)}
            />
            <View style={styles.line}/>
            <WebView
                ref={(ref) => {
                    this.webView = ref;
                }}
                automaticallyAdjustContentInsets={false}
                style={styles.webView}
                source={{uri: this.props.url}}
                injectedJavaScript={this.injectScript}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                decelerationRate="normal"
                startInLoadingState={true}
                scalesPageToFit={true}
            />
        </View>
    );
}
}

我用 injectScript 注入了一个函数

这个函数调用了Mwap组件的一个方法

我设置了window.mwap = this;

但在页面中,window.mwap 是未定义的

如何在 WebView 加载的网页中调用 React 组件方法?

请帮帮我

谢谢

【问题讨论】:

    标签: reactjs webview react-native


    【解决方案1】:

    您注入的 JavaScript 代码与您的 React Native JavaScript 代码没有任何联系。您在注入的 JS 中使用的 mwap 变量与您的组件没有任何关系。恐怕这种行为是不允许的。但是,您可以查看this answer 以获取替代方案,或查看react-native-webview-bridge 包。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-02
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 2016-12-26
      • 2021-09-26
      • 2020-08-21
      相关资源
      最近更新 更多