【问题标题】:How to replace jsx substring of a props - react如何替换道具的jsx子字符串 - 反应
【发布时间】:2021-08-02 09:36:36
【问题描述】:

我正在尝试创建一个共享表组件。而且,在这张桌子上,我试图让那些编辑 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 作为参数传递:const actionColumn = (ROW_ID) =&gt; (...) 然后&lt;td&gt;{actionColumn(row.id)}&lt;/td&gt;。或者将 actionColumn 设为行 ID 为道具的组件

标签: javascript reactjs


【解决方案1】:

改为创建一个函数,将 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>
))

还要注意你需要平衡你的&lt;tr&gt;标签;您目前有一个&lt;/tr&gt;,但没有匹配的&lt;tr&gt;

【讨论】:

【解决方案2】:

首先你需要让 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>
    ))}

【讨论】:

    猜你喜欢
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 2014-06-09
    • 2011-09-01
    • 2013-05-18
    • 2020-04-05
    相关资源
    最近更新 更多