javascript - 如何使用反应从父组件访问历史道具?
问题描述
我有一个方法 showInfo,由两个组件 Child1 和 Child2 访问。
最初我在 Child1 组件中有 showInfo 方法,如下所示
const Child1 = ({history}: RouteComponentProps) => {
type Item = {
id: string,
name: string,
value: string,
};
const showInfo = (item: item) => {
const id = item.id;
const value = item.value;
const handleRouteChange = () => {
const path = value === 'value1' ? `/value1/?item=${itemId}` : `/value2/?item=${itemId}`;
history.push(path);
}
return (
<Button onClick={handleRouteChange}> Info </Button>
);
}
return (
<SomeComponent
onDone = {({ item }) => {
notify({
actions: showInfo(item)
})
}}
/>
);
}
上面的代码有效。但现在我有另一个组件 child2 需要使用相同的方法 showInfo。
组件 child2 如下所示
const Child2 = () => {
return (
<Component
onDone = {({ item }) => {
notify({
actions: showInfo(item)
})
}}
/>
);
}
我没有在 Child2 组件中编写相同的方法 showInfo,而是将它放在不同的文件中,child1 和 child2 组件可以共享方法 showInfo。
下面是具有 showInfo 方法的名为 utils.tsx 的文件
export const showInfo = (item: item) => {
const id = item.id;
const value = item.value;
const handleRouteChange = () => {
const path = value === 'value1' ? `/value1/?item=${itemId}` :
`/value2/?item=${itemId}`;
history.push(path); //error here push is not identified as no
//history passed
}
return (
<Button onClick={handleRouteChange}> Info </Button>
);
}
return (
<SomeComponent
onDone = {({ item }) => {
notify({
actions: showInfo(item)
})
}}
/>
);
}
有了上面的内容,我得到了在 showInfo 方法中使用 history.push 的错误。推未定义。
这是因为这个文件 utils.tsx 中没有定义历史
现在的问题是如何从 child1 或 child2 组件传递历史记录。或者在这种情况下我可以访问历史的另一种方式是什么。
有人可以帮我解决这个问题。谢谢。
编辑:
child1 和 child2 中的 notify 来自 useNotifications,如下所示
const useNotifications = () => {
const [activeNotifications, setActiveNotifications] = React.useContext(
NotificationsContext
);
const notify = React.useCallback(
(notifications) => {
const flatNotifications = flatten([notifications]);
setActiveNotifications(activeNotifications => [
...activeNotifications,
...flatNotifications.map(notification => ({
id: notification.id,
...notification,
});
},
[setActiveNotifications]
)
return notify;
}
解决方案
虽然您可能会创建自定义挂钩,但您的函数会返回 JSX。这里有关于在自定义钩子中返回 JSX 的讨论。IMO,这与其说是一个实用程序或自定义钩子场景,不如说它是一个可重用的组件。这很好!
export const ShowInfo = (item: item) => { // capitalize
const history = useHistory(); // use useHistory
// ... the rest of your code
}
现在在 Child1 和 Child2 中:
return (
<SomeComponent
onDone = {({ item }) => {
notify({
actions: <ShowHistory item={item} />
})
}}
/>
);
您可能需要根据您的onDone
属性和notify
功能调整一些代码,但这种模式为您提供了您正在寻找的可重用行为。
推荐阅读
- ios - 在 AppStore Connect 中找不到缺少的 dSYM Crashlytics
- windows - 无法在 Windows 中安装 qutip
- python - 如何总结多个 csv 文件中的所有计数是否为零?
- c# - 如何在 Net Core MVC 模块化插件应用程序中注入多个启动配置文件?
- gatling - 如何在加特林报告中打印响应标题?
- swagger - 在我的招摇页面上选择默认下拉值
- .htaccess - 如何将流量从 http://mydomain.com.br-my-account 重定向到端口 443 (.htaccess)?
- apache - Apache LimitRequestBody 被忽略
- ios - Firebase 云消息广播由捆绑 ID 或 firebase 项目 (GoogleService-Info.plist) 确定
- c# - 使用 ProgressBar 作为 StackPanel 背景