我的代码取自官方 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"));
Run Code Online (Sandbox Code Playgroud)
当调用 focusTextInput 时,它会记录“current: null”。这是演示:https : //codesandbox.io/s/wo6qjk9xk7
代码很好,因为它与react 文档中的示例完全相同。问题是您的react-dom版本较旧。React.createRef()API 是在 React 16.3 中引入的(所有react相关的包都应该是 16.3+ 才能使用React.createRef())。检查文档中的此参考。
您的依赖项:
"dependencies": {
"react": "16.6.3",
"react-dom": "16.2.0"
},
Run Code Online (Sandbox Code Playgroud)
更新react-dom到 16.6.3后问题已修复
检查这个:https : //codesandbox.io/s/n7ozx9kr0p
| 归档时间: |
|
| 查看次数: |
6455 次 |
| 最近记录: |