React-router:使用<Link>作为可点击的数据表行

jfr*_*rye 18 javascript reactjs react-router

我是新手使用ReactJS和react-router.我想要一个可点击的表格行,如下所示:

<Link to=“#”>
<tr>
    <td>{this.props.whatever1}</td>
    <td>{this.props.whatever2}</td>
    <td>{this.props.whatever3}</td>
</tr>
</Link>
Run Code Online (Sandbox Code Playgroud)

但我知道你不能<a><tbody><tr>标签之间放置标签.我怎么能做到这一点?

PS:如果可能的话我不想使用jQuery.

Igo*_*hin 16

onClick有效,但有时你需要一个实际的<a>标签出于各种原因:

  • 无障碍
  • 渐进增强(如果脚本抛出错误,链接仍然有效)
  • 能够在新标签中打开链接
  • 能够复制链接

对于类似的情况,我最终创建了一个Td组件:

import React, { PropTypes } from 'react';
import { Link } from 'react-router';

import styles from './styles.css';

const propTypes = {
  children: PropTypes.node.isRequired,
  to: PropTypes.string,
};

function Td({ children, to }) {
  // Conditionally wrapping content into a link
  const content = to ? (
    <Link className={styles.content} to={to}>{children}</Link>
  ) : (
    <div className={styles.content}>{children}</div>
  );

  return (
    <td>
      {content}
    </td>
  );
}

Td.propTypes = propTypes;

export default Td;
Run Code Online (Sandbox Code Playgroud)

使按钮填充整个单元格的样式:

.content {
  display: block;
  color: inherit;
  padding: 5px 10px;
}
Run Code Online (Sandbox Code Playgroud)

然后使用这样的组件:

const users = this.props.users.map((user) =>
      <tr key={user.id}>
        <Td to={`/users/${user.id}/edit`}>{user.name}</Td>
        <Td to={`/users/${user.id}/edit`}>{user.email}</Td>
        <Td to={`/users/${user.id}/edit`}>{user.username}</Td>
      </tr>
    );
Run Code Online (Sandbox Code Playgroud)

是的,您必须多次传递to道具,但同时您可以更好地控制可点击区域,并且您可能在表格中有其他互动元素,例如复选框.

  • 但你最终会得到无效的 html(div 作为 tr 的孩子) (2认同)
  • 刚刚检查。td中的Div是合法的:https://www.dropbox.com/s/l24ioflyjjxjuq6/Screenshot%202017-02-28%2010.40.59.png?dl=0 (2认同)
  • @DragonKnight,您可能可以使用“Link”并使用“display:table-row”对其进行样式设置。我还没试过 (2认同)

Ser*_*res 5

你为什么不用onClick?

var ReactTable = React.createClass({
  handleClick: function(e) {
    this.router.transitionTo('index');
  },
  render: function() {
    return(
      <div>
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Age</th>
              <th>Full Detail</th>
            </tr>
          </thead>
            <tbody>
              <tr onClick={this.handleClick.bind(this)}>
                <td>{user.name}</td>
                <td>{user.age}</td>
                <td>{details}</td>
              </tr>
            </tbody>
        </table>
      </div>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 然后,您无法使用右键单击选项,例如在新选项卡中打开.这可能对表特别有用. (20认同)
  • 以上不是上下文菜单,而是“在新标签页/窗口中打开”的常见模式-无论您是通过右键单击,cmd / ctrl单击,长按还是其他方式执行此操作。 (4认同)
  • 它抑制高级用户和残障用户 (2认同)