我在这里阅读了很多答案,但它们都是类组件的潮流。
如果我有使用 useRef 或 createRef 的简单功能组件,则 ref.current 未定义
我将它分配在 div 或 input 之上,但我无法获取它们的任何属性
Console.log() 仅当我使用独立 console.log(ref) 时才给我数据
所有其他属性都是未定义的,例如console.log(ref.当前)
import React, { useRef } from "react";
import ReactDOM from "react-dom";
function App() {
const ref = useRef()
console.log(ref.current) // undefined
console.log(ref) // { current }
return (
<div className="App">
<h1 ref={ref}>Hello CodeSandbox</h1>
{/* <input ref={ref} name="test" value="bla" /> */}
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
看看这个演示并查看控制台:https://codesandbox.io/s/fervent-kirch-soe8n https://codesandbox.io/s/fervent-kirch-soe8n
但即使在类组件中,我也无法访问例如 ref.current.innerHTML:https://codesandbox.io/s/relaxed-beaver-ic1em https://codesandbox.io/s/relaxed-beaver-ic1em
好的我已经找到问题所在了。
如果我使用 useEffect() 或者如果我使用一些按钮处理程序,我可以访问元素:
useEffect(()=>{
console.log(ref.current.innerHTML)
})
类组件中相同:
class App extends React.Component {
myRef = React.createRef();
componentDidMount(){
console.log(this.myRef.current); // correct
}
render() {
console.log(this.myRef.current); // null
return <h2 ref={this.myRef}>Start editing to see some magic happen!</h2>
}
}
or
<button onClick={()=> console.log(ref.current.innerHTML)}>Click</button>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)