【发布时间】:2015-08-31 06:05:21
【问题描述】:
我正在尝试在 ReactJS 中构建一个表,该表为数组中的每个元素生成两行。我无法解决的问题是以行(n)可以向行(n+1)发送消息的方式生成它们。
如果单击其中一行,此应用程序将打开详细视图。
现在我的方法是生成行并将 row(n+1) 作为行的 prop 传递。
const orders = [
// this is just some example data
{
"name": "lorem",
"number": "20.00",
"price": "20.00",
"image": "http://localhost/path/to/image1.jpg"
},
{
"name": "lorem",
"number": "20.00",
"price": "20.00",
"image": "http://localhost/path/to/image1.jpg"
},
];
const Orders = React.createClass({
renderAllRows(order) {
// this function would generate all the rows of the table
const rows = [];
orders.map(function (order, index) {
const OrderDetailInstance = <OrderDetail display={false} item={order} />
// OrderDetailInstance is passed as a prop of OrderItemInstance
const OrderItemInstance = <OrderItem detail={OrderDetailInstance} item={order}/>;
rows.push(OrderItemInstance, OrderDetailInstance);
});
return rows;
},
render() {
const { state } = this;
const { orders } = state;
const { isLastPage } = state;
return (
<Table>
<tbody>
{this.renderAllRows(orders).map(function(row) {
return row;
})}
</tbody>
</Table>
);
},
});
但是这不起作用,因为当 prop 成功通过时,我不知道如何访问 react 元素上的方法。所以我显然是在解决这个问题。
目前这是我在反应元素上调用方法的不成功方法。
const OrderItem = React.createClass({
render() {
const item = this.props.item;
return (
<tr>
<td>{item.number}</td>
<td>{item.number}</td>
<td>
<a onClick={this.openOrderDetail}>open detail</a>
</td>
</tr>
);
},
openOrderDetail() {
// This is where I'm trying to call the prop's method.
this.props.detail.open();
}
});
const OrderDetail = React.createClass({
render() {
const display = this.props.display;
const classes = display ? classNames('') : classNames('hidden');
return (
<tr className={classes}>
<td colSpan="3">
<div>
This is the detail of the previous row
</div>
</td>
</tr>
);
},
open() {
// This should IDEALLY be exposed to any react element that has
// OrderDetail as a prop.
console.log("open");
}
});
我对使用 Orders 类的状态的想法持开放态度,但我不禁觉得这太过分了。
【问题讨论】:
-
为长代码示例道歉,我知道这不是必需的,但有时上下文很有用:-)
标签: javascript reactjs reactjs-flux