在 React Material UI 表中使用按钮

新手上路,请多包涵

我使用 Material UI 制作了一个表格,其中每一行的第一列都有两个按钮。我希望通过单击这些行来编辑/删除行,但我坚持逻辑。我的实施甚至有可能吗?如果不是,那么这样做的首选方式是什么?

 render() {
  var deleteIcon =
  (<IconButton onClick={console.log("delete")}>
    <DeleteIcon color="secondary" />
  </IconButton>
  );

  const editIcon = (
    <IconButton onClick={console.log("edited")}>
      <EditIcon color="primary" />
    </IconButton>
  );

return(
  <TableBody>
   {this.state.serviceData.map(n => {
    return (
     <TableRow key={n.id}>
      <TableCell style={styles.editor} component="th" scope="row">
        {deleteIcon}
        {editIcon}
      </TableCell>
     <TableCell>{n.domain}</TableCell>
   <TableCell>{n.service_name}</TableCell>
  </TableCell>
 </TableRow>
)};

我的结果是: 图片显示我的桌子

原文由 Yashank 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 315
2 个回答

基于@st4rl00rd 的评论,我能够使用以下方法绑定按钮:

 const editIcon = (
      <IconButton onClick={this.editItem}>
        <EditIcon color="primary" />
      </IconButton>
    );

并将它们绑定到构造函数中。我能够通过执行以下操作获取选定的行数据:

        <TableBody>
            {this.state.serviceData.map(n => {
              return (
                <TableRow key={n.id} onClick={this.getData.bind(this,n)}>

原文由 Yashank 发布,翻译遵循 CC BY-SA 4.0 许可协议

我已经重新创建了你的问题并用我的逻辑解决了问题。

我将每个元素的 index 作为参数传递给处理函数。

例如:

 const editIcon = index => (
      <IconButton onClick={() => this.editComponent(index)}>
        <EditIcon color="primary" />
      </IconButton>
    );

删除

对于删除,将索引作为参数传递给处理函数,并使用 splice 运算符删除指定索引处的元素。

 deleteComponent(index) {
    const serviceData = this.state.serviceData.slice();
    serviceData.splice(index, 1);
    this.setState({ serviceData });
  }

编辑

我使用了一个名为 index 的状态来跟踪用户当前正在编辑的索引。最初 index 是-1

因此,每当用户单击编辑按钮时, editedIndex 都会更新。

 editComponent(index) {
    this.setState({ editedIndex: index });
  }

我创建了两个 TextField 组件,它显示在指定的单元格(单击编辑按钮的单元格)

 const editDomain = (
      <TextField
        id="domain"
        label="Domain"
        className={classes.textField}
        value={this.state.editedDomain}
        margin="normal"
        onChange={this.handleChange('editedDomain')}
      />
    );

因此,每当渲染组件索引等于编辑索引时,编辑组件就会显示在相应的 Tablecell 中

 <TableCell>
  {serviceData.indexOf(n) === editedIndex
    ? editDomain
    : n.domain}
</TableCell>

原文由 noName94 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题