简体   繁体   中英

react typescript create ref to access state of child

I want to access the state of child component in the parent component, I don't want to use any handlers in child component that can set a variable in parent or I don't want to lift the state up in parent. How can I use ref in react typescript to createRef and get the child's state in the parent component?

Parent:

export interface ParentProps {}

interface State {
    counter?: number
}

export class Parent extends React.Component<ParentProps, State> {
    private readonly childRef: React.RefObject<**what should I put here?**>
    constructor(props: ParentProps) {
        super(props)
        this.state = {
            counter: undefined
        }
        this.childRef = React.createRef<**what should I put here**>();
    }

    render(){
        <Child ref={childRef} **<- (this throws an error)** counter={this.state.counter}
        <button onClick={() => this.setState({counter: this.state.counter + 1})}>
             add
        </button>
    }
}

Child:

export interface ChildProps {
  counter: number
}
    
interface State {
  some state variable that should be accessible in parent
}
    
export class Child extends React.Component<ChildProps, State> {
   some methods...
}

You may try

this.childRef = React.createRef<Child>(null);

render(){
        <Child ref={this.childRef}  counter={this.state.counter} />
        <button onClick={() => this.setState({counter: this.state.counter + 1})}>
             add
        </button>
    }

private readonly childRef: React.RefObject<Child>

or

private readonly childRef: React.RefObject<Child>()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM