首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >在表格的行单元格内添加物料界面的单选按钮。

在表格的行单元格内添加物料界面的单选按钮。
EN

Stack Overflow用户
提问于 2017-08-29 14:52:25
回答 3查看 6.1K关注 0票数 1

我现在的设计是这样的

我正在使用Material UI的单选按钮,我想让每行只选择一次。添加<RadioButton>组件时,我可以选择它,但不能在行之间切换

代码语言:javascript
运行
AI代码解释
复制
  transactionRow(member: Object) {
    return (
      <tr id='drawLotteryTabel' style={styles.tr} key={member.uuid}>
        <td className="col-md-2 col-xs-2">{member.user.fullName}</td>
        <td className="col-md-1 col-xs-1">{this.getSubscriptionDropDown(member.subscriptions)}</td>
        <td className="col-md-2 col-xs-2">{CommonConstants.INR_SYMBOL + ' ' + Utils.formatNumberLocalised(member.bidDiscountAmount || 0)}</td>
        <td className="col-md-2 col-xs-2">{CommonConstants.INR_SYMBOL + ' ' + Utils.formatNumberLocalised(member.bidDiscountPercent || 0)}</td>
        <td className="col-md-2 col-xs-2">{CommonConstants.INR_SYMBOL + ' ' + Utils.formatNumberLocalised(member.unpaidAmount || 0)}</td>
        <td
          className="col-md-2 col-xs-2"
        >
          <RadioButtonGroup name="shipSpeed" defaultSelected="not_light" key={member.uuid}>
            <RadioButton
              value="light"
              style={styles.radioButton}
            />
          </RadioButtonGroup></td>
      </tr>

    );
  }

上述代码的结果如下所示

我应该怎么做才能将整个表行作为单个实体进行选择。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-08-29 20:59:04

不幸的是,您可能需要手动管理单选按钮的状态,将其作为受控组件。

RadioButtonGroup包含对存储所选值的onChange函数的调用:

代码语言:javascript
运行
AI代码解释
复制
handleChange: (event, value) => {
    this.setState({selectedButtonValue: value});
}

然后使用valueSelected属性将该值推送到每个RadioButtonGroup;

代码语言:javascript
运行
AI代码解释
复制
<RadioButtonGroup name="shipSpeed" defaultSelected="not_light" key={member.uuid}
    onChange={this.handleChange}
    valueSelected={this.state.selectedButtonValue}
>
票数 3
EN

Stack Overflow用户

发布于 2020-06-10 09:29:04

我假设您使用的是material ui中的"Enhanced Table“。如果是这样的话

替换

代码语言:javascript
运行
AI代码解释
复制
    if (selectedIndex === -1) {
      newSelected = newSelected.concat(selected, name);
    } else if (selectedIndex === 0) {
      newSelected = newSelected.concat(selected.slice(1));
    } else if (selectedIndex === selected.length - 1) {
      newSelected = newSelected.concat(selected.slice(0, -1));
    } else if (selectedIndex > 0) {
      newSelected = newSelected.concat(
        selected.slice(0, selectedIndex),
        selected.slice(selectedIndex + 1),
      );
    }

使用

代码语言:javascript
运行
AI代码解释
复制
    if (selectedIndex === -1) {
      newSelected = [name];
    }

并替换

带有单选组件的Checkbox组件。

改变这一点

代码语言:javascript
运行
AI代码解释
复制
<TableCell padding="checkbox">
    <Checkbox
     checked={isItemSelected}
     inputProps={{ 'aria-labelledby': labelId }}
     />
 </TableCell>

到这个

代码语言:javascript
运行
AI代码解释
复制
<TableCell padding="checkbox">
     <Radio
      checked={isItemSelected}
      inputProps={{ 'aria-labelledby': labelId }}
      />
</TableCell>

您应该能够在单选按钮之间切换,因为该按钮仅在新行被选中时才会激活,并且它会替换旧的选中状态。

我附上了材料ui增强表的实现与单选按钮的实现。我在这里和那里做了一些调整。你可以看一看。

代码语言:javascript
运行
AI代码解释
复制
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { lighten, makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TablePagination from '@material-ui/core/TablePagination';
import TableRow from '@material-ui/core/TableRow';
import TableSortLabel from '@material-ui/core/TableSortLabel';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Radio from '@material-ui/core/Radio';
// import IconButton from '@material-ui/core/IconButton';
// import Tooltip from '@material-ui/core/Tooltip';
// import FormControlLabel from '@material-ui/core/FormControlLabel';
// import Switch from '@material-ui/core/Switch';
// import DeleteIcon from '@material-ui/icons/Delete';
// import FilterListIcon from '@material-ui/icons/FilterList';

function createData(name, calories, fat, carbs, protein) {
  return { name, calories, fat, carbs, protein };
}

const rows = [
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Donut', 452, 25.0, 51, 4.9),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
  createData('Honeycomb', 408, 3.2, 87, 6.5),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Jelly Bean', 375, 0.0, 94, 0.0),
  createData('KitKat', 518, 26.0, 65, 7.0),
  createData('Lollipop', 392, 0.2, 98, 0.0),
  createData('Marshmallow', 318, 0, 81, 2.0),
  createData('Nougat', 360, 19.0, 9, 37.0),
  createData('Oreo', 437, 18.0, 63, 4.0),
];

function descendingComparator(a, b, orderBy) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

function getComparator(order, orderBy) {
  return order === 'desc'
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy);
}

function stableSort(array, comparator) {
  const stabilizedThis = array.map((el, index) => [el, index]);
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });
  return stabilizedThis.map((el) => el[0]);
}

const headCells = [
  { id: 'name', numeric: false, disablePadding: true, label: 'Dessert (100g serving)' },
  { id: 'calories', numeric: true, disablePadding: false, label: 'Calories' },
  { id: 'fat', numeric: true, disablePadding: false, label: 'Fat (g)' },
  { id: 'carbs', numeric: true, disablePadding: false, label: 'Carbs (g)' },
  { id: 'protein', numeric: true, disablePadding: false, label: 'Protein (g)' },
];

function EnhancedTableHead(props) {
  const { classes, order, orderBy, onRequestSort } = props;
  const createSortHandler = (property) => (event) => {
    onRequestSort(event, property);
  };

  return (
    <TableHead>
      <TableRow>
        <TableCell padding="checkbox">
        </TableCell>
        {headCells.map((headCell) => (
          <TableCell
            key={headCell.id}
            align={headCell.numeric ? 'right' : 'left'}
            padding={headCell.disablePadding ? 'none' : 'default'}
            sortDirection={orderBy === headCell.id ? order : false}
          >
            <TableSortLabel
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : 'asc'}
              onClick={createSortHandler(headCell.id)}
            >
              {headCell.label}
              {orderBy === headCell.id ? (
                <span className={classes.visuallyHidden}>
                  {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                </span>
              ) : null}
            </TableSortLabel>
          </TableCell>
        ))}
      </TableRow>
    </TableHead>
  );
}

EnhancedTableHead.propTypes = {
  classes: PropTypes.object.isRequired,
  onRequestSort: PropTypes.func.isRequired,
  onSelectAllClick: PropTypes.func.isRequired,
  order: PropTypes.oneOf(['asc', 'desc']).isRequired,
  orderBy: PropTypes.string.isRequired,
  rowCount: PropTypes.number.isRequired,
};

const useToolbarStyles = makeStyles((theme) => ({
  root: {
    paddingLeft: theme.spacing(2),
    paddingRight: theme.spacing(1),
  },
  highlight:
    theme.palette.type === 'light'
      ? {
          color: theme.palette.secondary.main,
          backgroundColor: lighten(theme.palette.secondary.light, 0.85),
        }
      : {
          color: theme.palette.text.primary,
          backgroundColor: theme.palette.secondary.dark,
        },
  title: {
    flex: '1 1 100%',
  },
}));

const EnhancedTableToolbar = (props) => {
  const classes = useToolbarStyles();
  const { numSelected } = props;

  return (
    <Toolbar
      className={clsx(classes.root, {
        [classes.highlight]: numSelected.length > 0,
      })}
    >
      {numSelected.length > 0 ? (
        <Typography className={classes.title} color="inherit" variant="subtitle1" component="div">
          {numSelected}
        </Typography>
      ) : (
        <Typography className={classes.title} variant="h6" id="tableTitle" component="div">
          Nutrition
        </Typography>
      )}

      {/* {numSelected.length > 0 ? (
        <Tooltip title="Delete">
          <IconButton aria-label="delete">
            <DeleteIcon />
          </IconButton>
        </Tooltip>
      ) : (
        <Tooltip title="Filter list">
          <IconButton aria-label="filter list">
            <FilterListIcon />
          </IconButton>
        </Tooltip>
      )} */}
    </Toolbar>
  );
};

EnhancedTableToolbar.propTypes = {
  numSelected: PropTypes.string.isRequired,
};

const useStyles = makeStyles((theme) => ({
  root: {
    width: '100%',
  },
  paper: {
    width: '100%',
    marginBottom: theme.spacing(2),
  },
  table: {
    minWidth: 750,
  },
  visuallyHidden: {
    border: 0,
    clip: 'rect(0 0 0 0)',
    height: 1,
    margin: -1,
    overflow: 'hidden',
    padding: 0,
    position: 'absolute',
    top: 20,
    width: 1,
  },
}));

export default function EnhancedTableWithRadio() {
  const classes = useStyles();
  const [order, setOrder] = React.useState('asc');
  const [orderBy, setOrderBy] = React.useState('calories');
  const [selected, setSelected] = React.useState('');
  const [page, setPage] = React.useState(0);
  // const [dense, setDense] = React.useState(false);
  const [rowsPerPage, setRowsPerPage] = React.useState(5);

  const handleRequestSort = (event, property) => {
    const isAsc = orderBy === property && order === 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(property);
  };


  const handleClick = (event, name) => {
    let newSelected = selected;

    if (name !== selected) {
      newSelected = name;
    }
    setSelected(newSelected);
  };

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  // const handleChangeDense = (event) => {
  //   setDense(event.target.checked);
  // };

  const isSelected = (name) => selected.indexOf(name) !== -1;

  const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage);

  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
      <EnhancedTableToolbar numSelected={selected} />
        <TableContainer>
          <Table
            className={classes.table}
            aria-labelledby="tableTitle"
            // size={dense ? 'small' : 'medium'}
            size = "medium"
            aria-label="enhanced table"
          >
            <EnhancedTableHead
              classes={classes}
              order={order}
              orderBy={orderBy}
              onRequestSort={handleRequestSort}
              rowCount={rows.length}
            />
            <TableBody>
              {stableSort(rows, getComparator(order, orderBy))
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map((row, index) => {
                  const isItemSelected = isSelected(row.name);
                  const labelId = `enhanced-table-checkbox-${index}`;

                  return (
                    <TableRow
                      hover
                      onClick={(event) => handleClick(event, row.name)}
                      role="checkbox"
                      aria-checked={isItemSelected}
                      tabIndex={-1}
                      key={row.name}
                      selected={isItemSelected}
                    >
                      <TableCell padding="checkbox">
                        <Radio
                          checked={isItemSelected}
                          inputProps={{ 'aria-labelledby': labelId }}
                        />
                      </TableCell>
                      <TableCell component="th" id={labelId} scope="row" padding="none">
                        {row.name}
                      </TableCell>
                      <TableCell align="right">{row.calories}</TableCell>
                      <TableCell align="right">{row.fat}</TableCell>
                      <TableCell align="right">{row.carbs}</TableCell>
                      <TableCell align="right">{row.protein}</TableCell>
                    </TableRow>
                  );
                })}
              {emptyRows > 0 && (
                <TableRow style={{ height: 53 * emptyRows }}>
                {/* <TableRow style={{ height: (dense ? 33 : 53) * emptyRows }}> */}
                
                  <TableCell colSpan={6} />
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <TablePagination
          rowsPerPageOptions={[5, 10]}
          component="div"
          count={rows.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onChangePage={handleChangePage}
          onChangeRowsPerPage={handleChangeRowsPerPage}
        />
      </Paper>
      {/* <FormControlLabel
        control={<Switch checked={dense} onChange={handleChangeDense} />}
        label="Dense padding"
      /> */}
    </div>
  );
}

票数 1
EN

Stack Overflow用户

发布于 2020-01-13 00:07:56

我在使用来自表的单元格中的单选按钮组件时也遇到了同样的问题,这两个组件都来自MaterialUi。我是这样决定的:

这是我的handleChange函数,用于选择我的应用程序所使用的Row.id的值

代码语言:javascript
运行
AI代码解释
复制
handleChange(field, event) {
        this.setState({[field] : event.target.value});
    }

在我的表格组件中,我只使用了"Radio“组件,而没有使用"RadioButtonGoup”组件。并在"Radio“组件的" checked”属性中使用一个条件,以将其显示为选中或未选中。

代码语言:javascript
运行
AI代码解释
复制
<Table aria-label="simple table">
   <TableHead>
      <TableRow>
         <TableCell align="center">Selecciona</TableCell>
         <TableCell>Brand</TableCell>
         <TableCell align="center">Tarjetahabiente</TableCell>
         <TableCell align="center">Terminación</TableCell>
         <TableCell align="center">Expira</TableCell>
         <TableCell align="center">Eliminar</TableCell>
      </TableRow>
   </TableHead>
   <TableBody>
      {rows.map(row => (
      <TableRow key={row.id}>
         <TableCell component="th" scope="row">
            <Radio
               value={row.id}
               defaultSelected={false}
               checked={row.id != this.state.paymentSourceId ? false : true}
               onChange={this.handleChange.bind(this, 'paymentSourceId')}
            />
         </TableCell>
         <TableCell align="center">{row.brand}</TableCell>
         <TableCell align="center">{row.name}</TableCell>
         <TableCell align="center">{row.last4}</TableCell>
         <TableCell align="center">{row.exp_month}/{row.exp_year}</TableCell>
         <TableCell align="center">
             <IconButton 
                 aria-label="delete" 
                 color="primary" 
                 onClick={()=>this.handleDelete(this.state.paymentSourceId)}>
                   <DeleteIcon />
              </IconButton>
         </TableCell>
      </TableRow>
      ))}
   </TableBody>
</Table>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45942257

复制
相关文章
wordpress文章内添加按钮
谷腾堡编辑器自带,提取出平时使用经典编辑器方便使用。理论高版本的wordpress都可以用吧。字体颜色也可以更改,用到了再去谷腾堡拿吧!
AlexTao
2019/12/12
9840
【HTML】HTML 表格总结 ★★★ ( 表格标签 | 行标签 | 单元格标签 | 表格标签属性 | 表头单元格标签 | 表格标题标签 | 合并单元格 )
表头单元格 可以在表格中 用作第一排 作为表格 的 表头 使用 , 表头单元格 中的 文本设置 可以与 普通单元格 中的文本设置 不同 ;
韩曙亮
2023/03/30
3.1K0
【HTML】HTML 表格总结 ★★★ ( 表格标签 | 行标签 | 单元格标签 | 表格标签属性 | 表头单元格标签 | 表格标题标签 | 合并单元格 )
Element Plus修改表格行、单元格样式
主要是通过 row-style属性来实现。它是行的 style的回调方法,可以通过它来实现设置某一行的样式。
赤蓝紫
2023/03/16
3.8K0
Element Plus修改表格行、单元格样式
单选按钮的用户体验设计
单选按钮是表单系统的一个基本元素。它们被使用在当存在互斥的两个或多个选项列表而用户必须选择其中一个时。换句话说,点选某个尚未选中的单选按钮,之前的选择就会恢复成未选中。 正确的使用单选按钮会非常好—
前朝楚水
2018/04/03
6.3K0
单选按钮的用户体验设计
HTML第二天
单选框:**<type=”radio” name=”sex” value=”nan” checked>**
小城故事
2023/02/27
3K0
HTML第二天
HTML的一些标签以及表单
通过给内容中特定位置加id值来标记位置,然后用<a href="#id名">来实现位置的跳转
小丞同学
2021/08/16
1.7K0
HTML单选表格和多选表格实现
单选表格 1 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" cont
治电小白菜
2020/08/25
7.7K0
HTML单选表格和多选表格实现
html学习笔记第二弹
表格标签的作用:主要用于显示、展示数据,因为它可以让数据显示的非常的规整,可读性非常好。特别是后台展示数据的时候,能够熟练运用表格就显得很重要。一个清爽简约的表格能够把繁杂的数据表现得很有条理。
是小北a
2022/03/28
3.9K0
html学习笔记第二弹
HTML初学
❤w3school快捷通道❤ ————————————————————————— Web标准构成的三部分:
且陶陶
2023/04/12
3.3K0
HTML初学
小白前端入门笔记(21),表单里如何添加单选按钮?
大家好,欢迎来到freecodecamp HTML专题第21篇,我们今天来聊聊单选按钮的使用。
TechFlow-承志
2021/04/16
1.8K0
小白前端入门笔记(21),表单里如何添加单选按钮?
【译】W3C WAI-ARIA最佳实践 -- 布局
面包屑包含当前页面的父页面的链接列表,该列表是层级顺序的。它可以帮助用户在网站或网络应用程序中找到自己的位置。面包屑通常水平放置在页面的主要内容之前。
韩宇波
2018/05/30
6.3K0
HTML知识框架 二
携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第20天,点击查看活动详情 >>
默默的成长
2022/11/02
2.1K0
单选按钮的取消与选中 原
(adsbygoogle = window.adsbygoogle || []).push({});
tianyawhl
2019/04/04
3.6K0
Flutter中的单选按钮组件Radio
Flutter 中的单选按钮组件有两种。 1. Radio 单选按钮,一般用来表现一些简单的信息。 常用属性如下: (1). value 单选的值; (2). onChanged 选择改变触发的事件; (3). activeColor 选中时的颜色; (4). groupValue 多个按钮选择组的值; 2. RadioListTile 包含更多信息的单选项,提供多种配置信息的属性,可以表现更丰富的信息。 常用的属性如下: (1). value 单选的值; (2). onChanged 选择改变触发的
越陌度阡
2021/01/05
9.7K0
Flutter中的单选按钮组件Radio
Flat风格的Qml单选/复选按钮
使用Qml的RadioButton与CheckBox控件修改而成。 单选按钮 RadioButton代码 import QtQuick 2.0 import QtQuick.Controls 2.0
Qt君
2019/11/24
2.4K0
【HTML】HTML 注册表单案例 ① ( 表格设置 | 设置表格位置和大小 | 设置表格标题 | 表单设置 | 表格中设置单选按钮 )
在 html 页面的 body 标签 中 , 通过 添加 table 标签 , 添加表格 ;
韩曙亮
2023/03/30
5.8K0
【HTML】HTML 注册表单案例 ① ( 表格设置 | 设置表格位置和大小 | 设置表格标题 | 表单设置 | 表格中设置单选按钮 )
Java 在PDF中添加表格
本文将介绍通过Java编程在PDF文档中添加表格的方法。添加表格时,可设置表格边框、单元格对齐方式、单元格背景色、单元格合并、插入图片、设置行高、列宽、字体、字号等。 通过maven导入 地址 代码如下:
崔笑颜
2020/06/08
4.7K0
点击加载更多

相似问题

如何向表格内的单选按钮添加单选组?

32

表格内的单选按钮

30

表格单元格的onClick选择单元格内的单选按钮。

17

单选按钮作为表格单元格

11

表格内的一组单选按钮

22
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文