以下是如何执行此操作的示例:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.passwordRef = React.createRef();
}
handleSubmit = e => {
this.passwordRef.current.focus();
};
render() {
return (
next
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(, rootElement);
CodeSandbox here .
另一种方式,使用孩子:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.passwordRef = React.createRef();
}
render() {
return (
);
}
}
const Child = ({ passwordRef }) => {
return passwordRef.current.focus()}>focus;
};
const rootElement = document.getElementById("root");
ReactDOM.render(, rootElement);
简答: this.ref.current 而不是 this.ref .