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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…