reactjs - 调用钩子函数以显示传入参数的钩子实例
问题描述
假设我有一个带有 ref containerRef 的 Container 钩子。
我希望能够使用传入参数的钩子实例调用 show 方法,以便在 MyContainer 中呈现钩子实例,如下所示:
<div>
<MyContainer ref={containerRef}/>
<button onClick={()=>containerRef.current.show(myHookInstance)}>click</button>
</div>
这是我的完整代码:
import React, {forwardRef, useImperativeHandle, useState} from 'react';
const MyContainer = forwardRef((props, ref) => {
const [showContent, setShowContent] = useState('');
useImperativeHandle(ref, () => ({
show: (content = null) => {
setShowContent(content)
},
}));
return (
<div>
this is the content:
{showContent}
</div>
)
})
const MyForm = () => {
const [name, setName] = useState("");
return (
<form>
<input type="text"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</form>
)
}
const App = () => {
const containerRef = React.createRef()
const myForm = MyForm()
return (
<div>
<MyContainer ref={containerRef}/>
<button onClick={()=>containerRef.current.show(myForm)}>click</button>
</div>
);
}
export default App;
问题是当我输入表单输入时,它没有显示出来。
据我了解,将钩子实例存储在状态中是一种非常糟糕的做法。
你有什么建议吗?
非常感谢您的帮助
解决方案
谢谢 Shubham,但实际上我需要 show 方法来接收任何内容作为参数,如下面的代码:
import React, {forwardRef, useImperativeHandle, useState} from 'react';
const MyContainer = forwardRef((props, ref) => {
const [showContent, setShowContent] = useState('');
useImperativeHandle(ref, () => ({
show: (content = null) => {
setShowContent(content)
},
}));
return (
<div>
this is the content:
{showContent}
</div>
)
})
const MyForm = () => {
const [name, setName] = useState("");
return (
<form>
<input type="text"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</form>
)
}
const AnotherContent = () => {
return (
<div>
Another content !
</div>
)
}
const App = () => {
const containerRef = React.createRef()
const myForm = <MyForm />
const anotherContent = <AnotherContent />
return (
<div>
<MyContainer ref={containerRef}/>
<button onClick={()=>containerRef.current.show(myForm)}>show MyForm</button>
<button onClick={()=>containerRef.current.show(anotherContent)}>show AnotherContent</button>
</div>
);
}
export default App;
你会如何改进它?
推荐阅读
- powershell - 仅导入 Excel 字符串中没有标题的数据 - PowerShell
- reactjs - ReactJS:表单向数据库发送错误的日期值
- php - 从字符串中删除特殊字符“|”,如果它包含“,”,则忽略开始|“结束”|
- javascript - console.log 不使用 await 变量记录
- c# - Masstransit Sagas 和自定义活动的依赖注入问题
- windows - Windows 安装程序在安装 git 期间挂起
- c++ - 为什么 Visual Studio 看不到我的 C++ 类之一?
- sql - 如何在每个分组结果后合并一个硬编码行
- c# - @Html.RenderPartialAsync() 与
标签助手 - c# - 编辑应用服务编辑器以调整我的 Azure 服务机器人的阈值