[英]How to replace jsx substring of a props - react
我正在嘗試創建一個共享表組件。 而且,在這張桌子上,我試圖讓那些編輯 url 動態。 代碼很簡單,看起來像:
const actionColumn = (
<Link
to={`/suppliers/ROW_ID/edit`}
className="btn btn-info btn-xs"
title="Edit"
>
<i className="fas fa-pencil-alt"></i>
</Link>
);
<Table
actionColumn={actionColumn}
/>
現在在桌子上,我想用ROW_ID
替換row.id
{list &&
list.map((row, i) => (
<tr>
<td>
{actionColumn.replace(
"ROW_ID",
row.id
)}
</td>
</tr>
))}
我嘗試使用.replace
但收到錯誤: actionColumn.replace is not a function
首先你需要讓 ActionColumn 成為一個接受 id 作為 props 的組件...然后導出組件
const ActionColumn = ({ id }) => (
<Link
to={`/suppliers/${id}/edit`}
className="btn btn-info btn-xs"
title="Edit"
>
<i className="fas fa-pencil-alt"></i>
</Link>
);
export default ActionColumn;
在此組件中,您導入 ActionColumn 組件並將 row.id 傳遞給它
{list &&
list.map((row, i) => (
<td>
<ActionColumn id={row.id} />
</td>
))}
制作一個 function 代替,將to
道具傳遞給鏈接:
const ActionColumn = ({ to }) => (
<Link
to={to}
className="btn btn-info btn-xs"
title="Edit"
>
<i className="fas fa-pencil-alt"></i>
</Link>
);
對於您的原始布局,您可以使用
<ActionColumn to={`/suppliers/ROW_ID/edit`} />
要進行不同的渲染,請傳遞不同的道具:
list.map((row, i) => (
<td>
<ActionColumn to={`/suppliers/${row.id}/edit`} />
</td>
))
另請注意,您需要平衡<tr>
標簽; 您目前有一個</tr>
但沒有匹配的<tr>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.