【问题标题】:How to Access React Context Inside a WebView in React Native?如何在 React Native 中访问 WebView 内的 React 上下文?
【发布时间】:2021-02-19 19:31:55
【问题描述】:

我希望能够在我的 WebView 中访问 React Context,但出现以下错误:

TypeError: undefined is not an object (evaluating 'Context._context')

这是我的代码:

// App.js

import React, { createContext } from 'react'
import { renderToString } from 'react-dom/server'
import { WebView } from 'react-native-webview'

export const AppContext = createContext({
    value: '',
    setValue: () => { }
})

export default function App() {
    const [value, setValue] = useState('Hello there')

    return (
        <AppContext.Provider value={{ value, setValue }}>
            <WebView source={{ html: renderToString(<WebViewComponent />) }} />
        </AppContext.Provider>
    )
}
// WebViewComponent.js

export default function WebViewComponent() {
    const { value, setValue } = useContext(AppContext)

    return (
        <div>
            {value}
        </div>
    )
}

【问题讨论】:

    标签: reactjs react-native webview react-context


    【解决方案1】:

    因此,解决问题的一个简单方法是将任何东西作为道具传递给renderToString(&lt;WebViewComponent /&gt;),而不是使用上下文。

    所以在我的例子中它会是这样的:

    // App.js
    
    import React from 'react'
    import { renderToString } from 'react-dom/server'
    import { WebView } from 'react-native-webview'
    
    export default function App() {
        const [value, setValue] = useState('Hello there')
    
        return (
            <WebView 
                source={{ 
                    html: renderToString(<WebViewComponent value={value} setValue={setValue} />) 
                }} 
            />
        )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2021-07-04
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多