【问题标题】:How to get rid of styling when using Link Component in React在 React 中使用链接组件时如何摆脱样式
【发布时间】:2020-07-04 22:23:26
【问题描述】:

我的应用程序中有一个表,当用户单击该表的一行时,他们会被重定向到应用程序的另一个页面。当我将链接组件应用于表格的每一行时,该行的样式就会变得混乱。

这就是它的实际外观(当我不将链接组件应用于表格的每一行时,它实际上看起来像这样):

当我将链接组件应用于表格的每一行时,它的外观如下:

下面是我用来渲染表格的代码:

  /*
  * Method for rendering the table
  * @param {Array} TableData - Table containing the list of products
  */
  renderTable = TableData => {
    return TableData.map((item, i) => (
      <tr key={i}>
        <Link to="/productServices/:productID">
        <td>1.</td>
        <td>{item.productName}</td>
        <td>{item.description}</td>
        <td>{item.department}</td>
        </Link>
      </tr>
    ));
  };

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: javascript css reactjs html-table react-router


    【解决方案1】:

    问题是您在 tr 标记中输入了无效的 HTML,它破坏了整个布局。

    您应该只使用tdth 来控制表格行的大小和流(tr)。您可以在 Table 行上使用 onClick 处理程序,但 这对可访问性不利,您将强制控制应用程序的导航

    下面是onClick 的样子:

      const handleNavigation = () => {
        // run react-router code for imperative navigation  
      }
    
      /*
      * Method for rendering the table
      * @param {Array} TableData - Table containing the list of products
      */
      renderTable = TableData => {
        return TableData.map((item, i) => (
          <tr key={i} onClick={handleNavigation}> 
            <td>1.</Link></td>
            <td>{item.productName}</td>
            <td>{item.description}</td>
            <td>{item.department}</td>
          </tr>
        ));
      };
    

    我的建议是在每个`td 中传递一个Link。它不会破坏样式,但也可以让用户点击表格行的任何位置并进行适当的导航:

      /*
      * Method for rendering the table
      * @param {Array} TableData - Table containing the list of products
      */
      renderTable = TableData => {
        return TableData.map((item, i) => (
          <tr key={i}> 
            <td><Link to="/productServices/:productID">1.</Link></td>
            <td><Link to="/productServices/:productID">{item.productName}</Link></td>
            <td><Link to="/productServices/:productID">{item.description}</Link></td>
            <td><Link to="/productServices/:productID">{item.department}</Link></td>
          </tr>
        ));
      };
    

    Here is a very simple example of the code above, on a simplified table. With the styling to make the link 100%.

    您可以将其进一步扩展为一个组件,您将使用该组件将表格单元格的内容包装在链接中并在您的表格中重复使用。

    【讨论】:

    • 首先感谢您的解释,我应用了这个技巧并且它正在工作,但是这个技巧的权衡是用户只有在他/她点击a中给出的文本信息时才会被重定向行(就像一个超链接),我想要的是用户应该通过点击行本身来重定向。关于如何实现该功能的任何想法。谢谢!
    • @AnmolSarraf 我在td 中添加了一个简单实现&lt;Link&gt; 的示例链接,带有样式。您可以看到,通过一个小的 CSS 更改,链接会占用整个单元格并且该行是可点击的。
    • 非常感谢@Inacio Schweller。你给出的例子完全符合我的需要。 :-)
    猜你喜欢
    • 2015-06-05
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多