Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在Vue组件中调用React组件的Context/Provider,不成功 #8

Open
Wowoy opened this issue Mar 24, 2022 · 2 comments
Open

在Vue组件中调用React组件的Context/Provider,不成功 #8

Wowoy opened this issue Mar 24, 2022 · 2 comments

Comments

@Wowoy
Copy link

Wowoy commented Mar 24, 2022

在Vue组件中调用React组件的Context/Provider 场景,不成功。

因为provider和context 组件的componentDidMount执行顺序有问题:
理应为:context先,provider 后;但是现状反过来了

@devilwjp
Copy link
Collaborator

@Wowoy 能提供一个范例吗?

@devilwjp
Copy link
Collaborator

devilwjp commented Apr 19, 2022

@Wowoy 亲测没有问题,见如下的范例

<template>
  <MyProvider :value="content">
    <!--  React组件中使用useContext  -->
    <ReactComponentInVue/>
  </MyProvider>
</template>

<script>
import { applyReactInVue } from 'vuereact-combined'
import { createContext, createElement, useContext } from 'react'

// React Context
const MyContext = createContext('default context value')

// A React Component
function ReactComponent() {
  const contextValue = useContext(MyContext)
  return createElement('div', {}, contextValue)
}

export default {
  data() {
    return {
      content: 'hahahahaha!'
    }
  },
  mounted() {
    clearInterval(this.timer)
    // 每秒变更React Context的value
    this.timer = setInterval(() => {
      this.content = 'context value:' + Math.random()
    }, 1000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  components: {
    ReactComponentInVue: applyReactInVue(ReactComponent),
    // 把Provider当作React组件直接转换
    MyProvider: applyReactInVue(MyContext.Provider),
  }
}
</script>

React函数组件ReactComponent通过useContext可以正常接收到Context的value变化

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants