Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

reactjs - How to use ref.current from context?

Hi i have ref in context.

// MyContextProvider
divRef = React.createContext<HTMLDivElement>();

componentDidMount() {
  this.divRef.current; // Ok
}

render() {
  return <MyContext.Provider value={{ divRef: this.divRef }} >{this.props.children}</MyContext.Provider>;
}

In the child component:

// MyComponent
componentDidMount() {
  this.context.divRef.current // Error Property 'current' does not exist on type '(instance: HTMLDivElement| null) => void'
}

render () {
  return <div ref={this.context.divRef}>example</div>;
}

when i trying to use divRef.current i getting Error:

any
Property 'current' does not exist on type 'RefObject | ((instance: HTMLDivElement | null) => void)'.
Property 'current' does not exist on type '(instance: HTMLDivElement | null) => void'.

But in the the Wrapper over the context (MyContextProvider) I can use and read the ref.current.

Also i've tried that:

if (this.context.divRef) {
  this.context.divRef.current // Same Error
}

Why ? How can i use divRef.current ?

P.S. Maybe i need to create 1 more ref in the child component, and already work with it, and assign it to the ref obtained from the context, but i don't know how to do it (i've tried use ref callback, but got a lot of errors):

something like this:

localRef = React.createRef<HTMLDivElement>();

render() {
  return (<div ref={(div) => {
    this.localRef = div;
    this.context.divRef = div;
  }}>
    example
  </div>);
}
question from:https://stackoverflow.com/questions/65904869/how-to-use-ref-current-from-context

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...