React ref 当前为 NULL
React ref current is NULL
我从官方 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 时,它会记录 "current: null"。
这是演示:https://codesandbox.io/s/wo6qjk9xk7
代码很好,因为它是文档中的 exact same example present in react docs. Problem is your react-dom
version is older. React.createRef()
API was introduced in React 16.3 (all react
related packages should be 16.3+ in order to use React.createRef()
). Check this reference。
您的依赖项:
"dependencies": {
"react": "16.6.3",
"react-dom": "16.2.0"
},
将 react-dom
更新到 16.6.3
后问题已解决
我从官方 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 时,它会记录 "current: null"。 这是演示:https://codesandbox.io/s/wo6qjk9xk7
代码很好,因为它是文档中的 exact same example present in react docs. Problem is your react-dom
version is older. React.createRef()
API was introduced in React 16.3 (all react
related packages should be 16.3+ in order to use React.createRef()
). Check this reference。
您的依赖项:
"dependencies": {
"react": "16.6.3",
"react-dom": "16.2.0"
},
将 react-dom
更新到 16.6.3