A ref
не является стандартной опорой.Вы можете изменить его на что-то другое (myRef
) или использовать ref forwarding :
const Hello = React.forwardRef((props, ref) => <input ref={ref} />);
Узел: ref forwarding работает с React 16.3 (не альфа)) и выше.
Демонстрация ( песочница ):
const Hello = React.forwardRef((props, ref) => <input ref={ref} />);
class TestRef extends React.Component {
ref = React.createRef();
componentDidMount() {
console.log(this.ref);
this.ref.current.focus(); // example of using the ref
}
render() {
return <Hello ref={this.ref} />;
}
}
ReactDOM.render(<TestRef />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>