尝试显示显示警报功能但遇到问题
这里我有一个带有按钮的父组件和一个带有显示警报功能的子组件。
但我收到此错误,
Function components cannot be given refs. Attempts to access this ref will fail.
代码:
import { useRef } from "react"
const ChildComp = () => {
function showAlert() {
alert("Hello from Child Component")
}
return <div></div>
}
function App() {
const childCompRef = useRef()
return (
<div>
<button>Click Me</button>
<ChildComp ref={childCompRef} />
</div>
)
}
export default App
有什么问题?
Here I have a parent component with a button and a child component with a function to show an alert.
but I was getting this error,
Function components cannot be given refs. Attempts to access this ref will fail.
code:
import { useRef } from "react"
const ChildComp = () => {
function showAlert() {
alert("Hello from Child Component")
}
return <div></div>
}
function App() {
const childCompRef = useRef()
return (
<div>
<button>Click Me</button>
<ChildComp ref={childCompRef} />
</div>
)
}
export default App
What's the issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你想传递引用,你必须在子组件中使用forwardRef。
Here you have to use forwardRef in child component if you want to pass refs.
当我们用
forwardRef
包围子组件时,它会接收到props
之外的第二个参数,即从parent 传递的
ref
组件。现在,借助此引用,我们可以指定父组件可以访问哪些函数。这可以使用
useImperativeHandle hook
来完成,如下所示:我发现这也很有帮助,StackOverflow
When we enclose the child component with
forwardRef
, it receives a second parameter apart fromprops
, which is theref
passed from theparent component
.Now with the help of this ref, we can specify which functions can be accessed by the
parent component
. This can be done usinguseImperativeHandle hook
, as shown below:I found this helpful as well, StackOverflow