反应打字稿创建引用以访问子状态

时间:2020-07-03 10:02:19

标签: node.js reactjs typescript react-typescript

我想访问父组件中子组件的状态,我不想在子组件中使用任何可以在父组件中设置变量的处理程序,或者我不想提升父组件中的状态。如何在react typescript中使用ref来创建ref并在父组件中获得子状态?

父母:

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>
    }
}

孩子:

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...
}

1 个答案:

答案 0 :(得分:0)

您可以尝试

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>

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