Основная проблема React.createRef<React.ReactElement>()
.Вам нужно изменить ReactElement
на нужный вам тип, в данном случае Child
.
Еще одна проблема в this.childRef.someFunction();
.Это отсутствует .current
.тогда это будет this.childRef.current.someFunction();
.
Вот полный пример:
Или попробуйте демо-версию на 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"));
Обновление -16 мая 2019 года:
Когда я открыл приведенный выше пример CodeSandBox и обновил его до последних зависимостей, он, похоже, не понравился:
childRef = React.createRef<Child>();
Выдает ошибку на закрывающей скобке )
.
Чтобы заставить его работать, я изменил его на:
childRef:React.RefObject<Child> = React.createRef();
![Edit gallant-ganguly-0puxy](https://codesandbox.io/static/img/play-codesandbox.svg)