React To Print自定义按钮点击无响应问题咨询
React To Print 自定义按钮无响应问题解决
问题原因
React To Print 的 trigger 函数会接收一个打印触发回调(handlePrint),并尝试将其绑定到返回组件的 onClick 属性上。但你的自定义组件 SqIconButton 并没有使用标准的 onClick 作为点击回调,而是自定义了 action 属性,导致 React To Print 注入的点击事件无法触发打印逻辑。
解决方案
方案一:直接传递打印触发函数到自定义按钮的 action 属性
修改 ReactToPrint 的 trigger 配置,接收 handlePrint 参数并传递给 SqIconButton 的 action:
<ReactToPrint trigger={(handlePrint) => <SqIconButton action={handlePrint} color="success"> <AiIcons.AiFillPrinter style={{color: 'black',fontSize:'1rem'}}/> </SqIconButton> } content={() => componentRef.current} />
这种方式完全适配你现有组件的 action 属性设计,不需要修改 SqIconButton 代码,是最直接的解决方法。
方案二:扩展自定义按钮支持标准 onClick(可选)
如果希望你的自定义按钮同时兼容标准 onClick 和自定义 action,可以修改 SqIconButton 组件,合并两种点击逻辑:
export default function SqIconButton({ children, color="primary", fontColor="#000000", action, tip="", disableElevation=false, sxstyle={}, classes, onClick // 添加标准 onClick 属性 }){ const handleClick = (e) => { // 优先执行自定义 action if (action) action(e); // 再执行标准 onClick(比如 ReactToPrint 注入的) if (onClick) onClick(e); }; return( <Tooltip title={tip}> <Button color={color} variant="contained" onClick={handleClick} disableRipple={disableElevation} className={`TBButton ${classes}`} sx={sxstyle} > {children} </Button> </Tooltip> ) }
修改后,原有的 ReactToPrint 写法也能正常工作,同时保留自定义 action 的扩展性。
额外说明
如果需要在触发打印前执行自定义逻辑,可以在 action 中包裹 handlePrint:
trigger={(handlePrint) => <SqIconButton action={(e) => { // 这里添加你的自定义逻辑,比如日志、状态更新 console.log("准备打印"); // 执行打印 handlePrint(); }} color="success" > <AiIcons.AiFillPrinter style={{color: 'black',fontSize:'1rem'}}/> </SqIconButton> }
内容的提问来源于stack exchange,提问作者Germán
相关产品推荐
相关产品推荐

