我试图在单击事件上向表中添加一行。这是我的组件:
import React, { Component } from 'react';
import PageContent from 'components/PageContent';
import { IBox, IBoxTitle, IBoxContent } from 'components/IBox';
import IBoxTools from 'components/IBoxTools';
import Table from 'components/Table';
export default class SalesChannelsPage extends Component {
constructor(props) {
super(props);
this.addRow = this.addRow.bind(this);
}
render() {
return (
<PageContent header="Salgskanaler">
<IBox>
<IBoxTitle>
Salgskanaler
<IBoxTools icon="fa fa-plus" title="Tilføj salgskanal" handleClick={() => this.addRow()}/>
</IBoxTitle>
<IBoxContent>
<Table>
<thead>
<tr>
<td className="channel-name">Navn</td>
<td className="channel-description">Beskrivelse</td>
<td className="channel-btn"></td>
</tr>
</thead>
<tbody>
</tbody>
</Table>
</IBoxContent>
</IBox>
</PageContent>
);
}
addRow() {
console.log('add row')
}
}
因此,每当我单击该按钮时,都应添加一个新行,并且应该可以向列表中添加尽可能多的行。这是我要添加的行。
我意识到我可以在状态中创建一个数组并将其放置在其中,但是我了解到只有数据应该包含在状态中。一些帮助将不胜感激。谢谢
<tr>
<td className="channel-name">
<input className="form-control input-sm" type="text" placeholder="Navn..." />
</td>
<td className="channel-description">
<input className="form-control input-sm" type="text" placeholder="Beskrivelse..." />
</td>
<td className="channel-btn">
<div>
<div className="btn btn-xs btn-danger"><span className="fa fa-times"></span></div>
<div className="btn btn-xs btn-primary"><span className="fa fa-floppy-o"></span></div>
</div>
</td>
</tr>
因此,正如马修·赫伯斯特(Matthew Herbst)所说,这就是状态。大概这些行需要显示某种数据。您不应该将HTML / JSX存储在数组中,但是应该存储用于在数组中构造列表的数据。这就是React的优点。您声明如何基于基础数据来呈现UI。然后,您只需操纵数据即可。因此,首先,您需要一个代表列表的状态数组。另外,您不需要将addRow
处理程序声明为由函数返回。它是一个功能。只是通过传递函数而不通过排除()
括号来调用它。最后,你map
在数组上,返回行。显然,这是没有数据的所有类型的转储,但是可以立即清楚地知道要在行中包含哪些数据。所以它应该看起来像这样:
import React, { Component } from 'react';
import PageContent from 'components/PageContent';
import { IBox, IBoxTitle, IBoxContent } from 'components/IBox';
import IBoxTools from 'components/IBoxTools';
import Table from 'components/Table';
export default class SalesChannelsPage extends Component {
constructor(props) {
super(props);
this.addRow = this.addRow.bind(this);
this.state = {
rows: []
}
}
render() {
return (
<PageContent header="Salgskanaler">
<IBox>
<IBoxTitle>
Salgskanaler
<IBoxTools icon="fa fa-plus" title="Tilføj salgskanal" handleClick={this.addRow}/>
</IBoxTitle>
<IBoxContent>
<Table>
<thead>
<tr>
<td className="channel-name">Navn</td>
<td className="channel-description">Beskrivelse</td>
<td className="channel-btn"></td>
</tr>
</thead>
<tbody>
{this.state.rows.map(row => <tr></tr>)}
</tbody>
</Table>
</IBoxContent>
</IBox>
</PageContent>
);
}
addRow() {
var nextState = this.state;
nextState.rows.push('placeholder');
this.setState(nextState);
}
}
再一次,我placeholder
每次只是将文本推到数组的末尾,因为我不知道在那里想要什么数据。但这会<tr>
在每次按下按钮时为您生成空标签。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句