我将此代码取自官方的React Ref文档
import React from "react";
import { render } from "react-dom";
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
// this.textInput.current.focus();
console.log(this.textInput);
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
const A = () => {
return <div>
<CustomTextInput />
</div>
}
render(<div><A/></div>, document.getElementById("root"));
,当调用focusTextInput时,它会记录“当前:空”。 这是演示:https://codesandbox.io/s/wo6qjk9xk7
答案 0 :(得分:2)
代码很好,因为它在React文档中有exact same example。问题是您的react-dom
版本较旧。 React.createRef()
API是在React 16.3中引入的
您的依赖项:
"dependencies": {
"react": "16.6.3",
"react-dom": "16.2.0"
},
将react-dom
更新为16.6.3后已解决的问题