【问题标题】:React's new Context API and Components with refReact 的新 Context API 和带有 ref 的组件
【发布时间】:2018-05-15 00:28:01
【问题描述】:

我得到:

"无状态函数组件不能被赋予refs。尝试 访问此引用将失败”。

当简单地用 MyContext.Provider 包装我的组件时;

(react-native,以及 reactjs 16.3.x )

新的 Context API 并没有说不能在 Consuming 组件也有 ref 时使用,但是它需要使用函数来获取上下文值,因此在某种程度上引入了“无状态”组件,没有的地方(我的组件都不是无状态的)。

有解决办法吗?

export const MyContext = React.createContext();


<MyContext.Provider  value={{'key':'val'}} >

  <MyContext.Consumer>

     {

         (contextVal)=> (
               <MyComponent  ref="find_me_later_22" globCx=contextVal>
          )

     }

  </MyContext.Consumer>

 </MyContext.Provider>

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    您需要重新转发您的 ref https://reactjs.org/docs/forwarding-refs.html

    import React, {createContext} from 'react';
    export const {Provider, Consumer} = createContext();
    
    export const WithContext = (WrappedComponent) => {
        return React.forwardRef((props, ref) => (
            <Consumer>
                {(value) => (
                    <WrappedComponent ref={ref} {...value} {...props}/>
                )}
            </Consumer>
        ))
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-22
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 2021-09-27
      • 1970-01-01
      • 2018-12-16
      • 2021-06-08
      相关资源
      最近更新 更多