我正在尝试弄清楚如何在我的项目中使用这个react-pdf 库。起初,我尝试将状态直接从 redux 存储渲染到react-pdf 组件中,但没有成功。
它显示错误:
could not find react-redux context value; please ensure the component is wrapped in a <Provider>
我有许多其他组件使用了 redux 中的状态,并且在我尝试在 和 中渲染来自react-pdf的组件之前,它们都没有这个问题。
这是我的代码的一部分:
const ConfigurationListPdf = (props)=> {
const mech = useSelector(mechConfig);
return(
<>
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>
{props.elem}
</Text>
</View>
</Page>
</Document>
</>
)
}
export default function InfoBoard(){
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
// Create Document Component
return(
<>
<CntrInfoBoard>
<InnerBoard>
<TitelDiv>
<Typography variant="h5" sx{{color:'white',fontWeight:900}}>Summary</Typography>
</TitelDiv>
<CntrInfoDetails>
<NodeTable/>
</CntrInfoDetails>
<Terms>
<p>
xxx
</p>
</Terms>
<PDFViewer>
<ConfigurationListPdf />
</PDFViewer>
<CntrSaveBtn>
<BtnSave>Configuration save</BtnSave>
<BtnOther>Sign up to finish</BtnOther>
<BtnOther onClick={savePdfHandler}>
{/*Save to PDF*/}
<PDFDownloadLinkStyled
document={<ConfigurationListPdf/>}
fileName="example.pdf"
>
Download PDF
</PDFDownloadLinkStyled>
</BtnOther>
</CntrSaveBtn>
</InnerBoard>
</CntrInfoBoard>
</>
)
}
如果代码格式有问题,抱歉。
只要我添加 useSelector 或 useDispatch 就会显示错误。
这很奇怪,因为它已经包含在我的index.js中:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App/>
</Provider>
</React.StrictMode>
);
我认为我的 redux 存储有问题,所以我尝试在不使用 React-pdf 的情况下调用其他组件中的状态和减速器,但事实证明并非如此。他们工作得很好。
有什么想法吗?
我在尝试渲染 PDF 内容时遇到了类似的问题。我认为问题在于
PDFViewer
和 PDFDownloadLink
组件渲染 iframe
元素,因此它们下面的 React 组件可能会从具有 Redux 提供程序的应用程序上下文渲染到单独的子 ReactTree 中。
为了解决这个问题,可以从 ReactTree 中比
PDFViewer
和 PDFDownloadLink
更高的位置访问 Redux 状态,例如在 InfoBoard
组件中,并将所选状态作为 props 传递给 ConfigurationListPdf
组件。
示例:
const ConfigurationListPdf = ({ elem, mech })=> {
// use mech prop now
return (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>
{elem}
</Text>
</View>
</Page>
</Document>
);
}
export default function InfoBoard() {
const mech = useSelector(mechConfig); // <-- select from Redux in parent
// Create Document Component
return (
<>
<CntrInfoBoard>
<InnerBoard>
....
<PDFViewer>
<ConfigurationListPdf mech={mech} /> // <-- pass mech as prop
</PDFViewer>
<CntrSaveBtn>
<BtnSave>Configuration save</BtnSave>
<BtnOther>Sign up to finish</BtnOther>
<BtnOther onClick={savePdfHandler}>
{/*Save to PDF*/}
<PDFDownloadLinkStyled
document={(
<ConfigurationListPdf
mech={mech} // <-- pass mech as prop
/>
)}
fileName="example.pdf"
>
Download PDF
</PDFDownloadLinkStyled>
</BtnOther>
</CntrSaveBtn>
</InnerBoard>
</CntrInfoBoard>
</>
);
}
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});