如何使用Material-UI将主要和次要文本水平而不是垂直对齐?

时间:2019-11-24 16:25:21

标签: material-ui

我有此代码:

import React from 'react';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import ArrowForwardIos from '@material-ui/icons/ArrowForwardIos';
import ListSubheader from '@material-ui/core/ListSubheader';
import Switch from '@material-ui/core/Switch';
import TextField from '@material-ui/core/TextField';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import Avatar from '@material-ui/core/Avatar';
import FolderIcon from '@material-ui/icons/Folder';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import DeleteIcon from '@material-ui/icons/Delete';
import IconButton from '@material-ui/core/IconButton';

function App() {
  return (
    <ListItem>
    <ListItemAvatar>
    <Avatar>
    <FolderIcon />
    </Avatar>
    </ListItemAvatar>
    <ListItemText
    primary="Single-line item"
    secondary="Secondary text"
    />
    <ListItemSecondaryAction>
    <IconButton edge="end" aria-label="delete">
    <DeleteIcon />
    </IconButton>
    </ListItemSecondaryAction>
    </ListItem>
  );
}

export default App;

enter image description here

“单行项目”和“辅助文本”在垂直方向上对齐,但是我需要在水平方向上对齐。你知道怎么做吗?

我需要在此处渲染右图,而不是左图:

enter image description here

https://gitlab.com/j4nos/tableitem/blob/master/src/App.js

如何? :)

2 个答案:

答案 0 :(得分:2)

我设法通过使用其他一些元素并参考了material-ui文档来获得所需的输出。这是一个有效的示例:https://codesandbox.io/s/sweet-bose-4e26h

function App() {
  return (
    <ListItem>
      <ListItemAvatar>
        <Avatar>
          <FolderIcon />
        </Avatar>
      </ListItemAvatar>
      <Box
        textAlign="right"
        style={{ paddingRight: 5 }}
      >
        Single-line item
      </Box>
      <ListItemText
        secondaryTypographyProps={{ align: "left" }}
        secondary="Secondary text"
      />
      <ListItemSecondaryAction>
        <IconButton edge="end" aria-label="delete">
          <DeleteIcon />
        </IconButton>
      </ListItemSecondaryAction>
    </ListItem>
  );
}

答案 1 :(得分:0)

ListItemText.classes.root上使用Material-UI的内置替代方法,如下所示:

 <ListItem className={classes.listItem}>
   <ListItemText
     classes={{ root: classes.listItemRootOverride }}
     className={classes.listText}
     primary={`${tc('Foo')}:`}
   />
   <ListItemText
    classes={{ root: classes.listItemRootOverride }}
    secondary={bars}
   />
 </ListItem>

useStyles中的类:

listItemRootOverride: {  /* this is the important one */
  flex: 'none',
  paddingRight: 4
},
listItem: {
  padding: theme.spacing(0)
},
listText: {
  color: theme.palette.common.black,
  paddingRight: theme.spacing(2)
}

示例输出(忽略次要对齐问题): Example output: