从父类调用子方法-React Typescript

时间:2018-10-11 20:06:51

标签: reactjs typescript react-redux

如何从父类调用子方法?还是简单地说如何将引用分配给ReactElement?

我已经看到了将ref分配给HTMLDivElement或HTMLInputElement而不是ReactElement的示例。

class Example extends React.Component<Props, State> {
  ...
  childRef = React.createRef<React.ReactElement>();
  ...
  next = () => {
    this.childRef.someFunction();
  }

  render() {
    <Child ref={this.childRef}/>
  }
}

上面的代码给了我两个错误:

Generic type 'ReactElement<P>' requires 1 type argument(s).
Property 'someFunction' does not exist on type 'RefObject<any>'.

3 个答案:

答案 0 :(得分:1)

使用React.createRef()时,生成的对象看起来像{current : null}。然后,React会将实际引用分配给refObject.current

因此,在您的示例中,您需要this.childRef.current.someFunction()

您可能还必须执行一些TypeScript声明,以使它知道ref内存储的对象具有可用的功能。

答案 1 :(得分:1)

主要问题是React.createRef<React.ReactElement>()。您需要将ReactElement更改为所需的类型,在这种情况下为Child

this.childRef.someFunction();中的另一期。它缺少.current。那么它将是this.childRef.current.someFunction();

这是一个完整的例子:

Or try live demo on CodeSandbox

import * as React from "react";
import { render } from "react-dom";

interface ChildState {
  lastCalled?: Date
}

class Child extends React.Component<{}, ChildState> {
  state: ChildState = {};

  render() {
    if (!this.state.lastCalled) {
      return "Not called yet";
    }

    return `Last called at ${this.state.lastCalled.toLocaleTimeString()}`;
  }

  someFunction = () => {
    this.setState({
      lastCalled: new Date()
    });
  };
}

class App extends React.Component {
  childRef = React.createRef<Child>();

  next = () => {
    if (!this.childRef.current) {
      return;
    }

    this.childRef.current.someFunction();
  };

  render() {
    return (
      <React.Fragment>
        <Child ref={this.childRef} />
        <div>
          <button type="button" onClick={this.next}>
            Next Call
          </button>
        </div>
      </React.Fragment>
    );
  }
}

render(<App />, document.getElementById("root"));

更新-2019年5月16日:

当我打开上面的CodeSandBox示例并更新到最新的依赖项时,它似乎并不喜欢:

childRef = React.createRef<Child>();

它在右括号)上引发错误。

为使其正常运行,我将其更改为:

childRef:React.RefObject<Child> = React.createRef();

Edit gallant-ganguly-0puxy

答案 2 :(得分:0)

我认为您需要传递一个函数来分配参考变量。

private childRef: any;
private assignRef = (ref) => this.childRef = ref;

next = () => {
    this.childRef.someFunction();
}

render() {
    <Child ref={this.assignRef}/>
}