嗨,我一直在使用這個包react-to-print來列印檔案,它作業得非常好。將值傳遞給子組件是可行的,我也可以列印動態資料。但是,我在傳遞陣列串列的動態資料時遇到問題。它總是獲取陣列的最后一項。我寫了一個例子,請看一下
import * as React from "react";
import { useRef } from "react";
import ReactToPrint from "react-to-print";
const ComponentToPrint = React.forwardRef((props, ref) => {
const { value } = props;
return (
<div className="print-source" ref={ref}>
Number {value}
</div>
);
});
export default function App() {
const componentRef = useRef();
const numbers = [1, 2, 3, 4, 5];
return (
<>
{numbers.map(function (item, index) {
return (
<div style={{ display: "flex" }}>
<li key={index}>{item}</li>
<ReactToPrint
trigger={() => <button type="primary">Print</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} value={item} />
</div>
);
})}
</>
);
}
現場演示
每當我單擊列印按鈕時,我都希望將 number 的唯一值發送到子組件,但每次我得到陣列的最后一個值。我究竟做錯了什么?
uj5u.com熱心網友回復:
因為只有一個componentRef實體,它在渲染順序上將具有最后渲染的值。
相反,每個回傳的組件App都需要有自己的componentRef.
這可以實作,如果你
- 也使從
App組件回傳的 html (比如說ComponentToPrintWrapper) - 有這個組件自己的
componentRef。
const ComponentToPrintWrapper = ({ item }) => { // 1.
const componentRef = useRef(); // 2.
return (
<div style={{ display: "flex" }}>
<li>{item}</li>
<ReactToPrint
trigger={() => <button type="primary">Print</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} value={item} />
</div>
);
};
- 改用
ComponentToPrintWrapper你App的
...
export default function App() {
const numbers = [1, 2, 3, 4, 5];
return (
<>
{numbers.map(function (item, index) {
return <ComponentToPrintWrapper key={index} item={item} />;
})}
</>
);
...
}
這將確保每個回傳元素都有自己的componentRef。
代碼沙盒
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/416309.html
標籤:
