React-admin:我可以在 <List> 中截断 <TextField> 吗?

React-admin: Can I truncate a <TextField> within a <List>?

有没有办法截断 <TextField> 返回的文本并显示 ...

参见下图中的 title 列(我想在 20 个字符后截断标题)。

有具体的prop吗?不幸的是,我没有在 react-admin 文档中找到任何线索。

提前致谢

您实际上可以操作 <List>
之外的任何字段,然后获取 <Datagrid> 来呈现该字段,只要因为它是迭代的。

const CustomTitleField = ({ record }) => {
  // "record" is a prop received from the Datagrid
  let str = record.title;
  return record ? (
    {/* If length is greater than 20 characters, slice and add ellipsis.*/}
    <span>{str.length > 20 ?  str.slice(0, 20) + "..." : str}</span>
  ) : null;
};

// Then, within your list, do this...
export const CommentList => (
  <List {...props}>
    <Datagrid>
      <CustomTitleField /> // this should render with your truncate logic
      // ...
    </Datagrid>
   </List>
);

尝试一下后告诉我进展如何!!

您可以使用 cellClassName 自定义 Datagrid 内的单元格样式。

https://marmelab.com/react-admin/Fields.html#styling-fields

我有一个类似的问题,这是对我有用的。

const useStyles = makeStyles((theme) => ({
  tableHeader: {
    fontWeight: "bold",
    textTransform: "capitalize",
  },
  tableCell: {
    maxWidth: 300,
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
    overflow: "hidden",
  }
}));

const MyList = ({ ...props }) => {
  const classes = useStyles();
  return (
    <List
      {...props}
    >
      <Datagrid>
        <TextField
          headerClassName={classes.tableHeader}
          cellClassName={classes.tableCell}
          source="detail"
          label="Detail"
        />
      </Datagrid>
    </List>
  );
};