【发布时间】:2020-07-28 12:49:35
【问题描述】:
我正在使用 HOC 组件将操作绑定到许多不同类型的元素,包括 SVG 单元格,当 onClick 正常绑定时,它可以工作,但是当我使用我的 HOC 时,它会返回意外的结果。
最小可重现示例:https://codesandbox.io/s/ecstatic-keldysh-3viw0
HOC 组件:
export const withReport = Component => ({ children, ...props }) => {
console.log(Component); //this only prints for ListItem elements for some reason
const { dispatch } = useContext(DashboardContext);
const handleClick = () => {
console.log('clicked!'); //even this wont work on some.
const { report } = props;
if (typeof report === "undefined") return false;
dispatch({ type: SET_ACTIVE_REPORT, activeReport: report });
dispatch({ type: TOGGLE_REPORT });
};
return (
<Component onClick={handleClick} {...props}>
{children}
</Component>
);
};
使用工作:
const ListItemWIthReport = withReport(ListItem); //list item from react-mui
{items.map((item, key) => (
<ListItemWithReport report={item.report} key={key} button>
{/* listitem children*/}
</ListItemWithReport>
))}
使用无效:
const BarWithReport = withReport(Bar); //Bar from recharts
{bars.map((bar, index) => (
<BarWithReport
report={bar.report}
key={index}
dataKey={bar.name}
fill={bar.fill}
/>
))}
ListItem 按预期 100% 工作,但是,条形图不会在 BarChart 内呈现。同样,使用 PieChart 时,单元格实际上会根据它们的值呈现正确的大小,但是,像“填充”这样的道具似乎不会传递下去。
我是否错误地使用了 HOC?我在 Charts 内部没有看到除 HOC 之外的选项,因为许多类型的元素将被视为无效 HTML?
【问题讨论】:
-
您如何在
handleClick中访问report? -
@rzwnahmd 我的错,我删除了它上面的行,因为我认为我没有使用它,代码破坏了道具,让我更新。
-
我认为
children在渲染范围内无效,因为Component(HOC 的第一个参数)基本上已经是孩子了?这也是我可以(直观地)看到示例一和示例二之间的唯一区别。 -
@bbortt 是的,我也是这么想的,但是,即使你只返回
<Component onClick={handleClick} {...props} />.,它仍然不起作用
标签: javascript reactjs react-hooks react-context recharts