我是使用ReactJS和react-router的新手。我想要一个可点击的表格行,类似于以下设置:
<Link to=“#”>
<tr>
<td>{this.props.whatever1}</td>
<td>{this.props.whatever2}</td>
<td>{this.props.whatever3}</td>
</tr>
</Link>
但我知道您无法在<a>
和<tbody>
代码之间添加<tr>
代码。我怎么能做到这一点?
PS:如果可能,我不想使用jQuery。
答案 0 :(得分:14)
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;
使按钮填满整个单元格的样式:
.content {
display: block;
color: inherit;
padding: 5px 10px;
}
然后使用这样的组件:
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>
);
是的,您必须多次通过to
道具,但同时您可以更好地控制可点击区域,并且您可能在表格中有其他互动元素,例如复选框。
答案 1 :(得分: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>
);
}
});
答案 2 :(得分:-1)
{shipment.assets.map((i, index) => (
<tr
style={{ cursor: "pointer" }}
onClick={(e) => e.preventDefault()}
>
<td>{index + 1}</td>
<td>{i._id}</td>
<td>{i.status}</td>
<td></td>
</tr>
))}