Как установить стиль для компонента act.js при его создании?
Как установить стиль для компонента act.js при его создании?
Ниже приведен фрагмент моего кода (частично унаследованный от более сильного разработчика, а затем упрощенный для краткости).
Я хочу повторно использовать мой LogComponent для печати нескольких страниц журнала. Однако в некоторых случаях я хочу навязать определенную ширину возвращаемому списку, а не позволять ему сгибаться по своему усмотрению.
Я бы предпочел не определять отдельный LogComponentFixed или иметь if (...) {return (...)} else {return(...)}
в моем LogComponent.
Я имею в виду сделать что-то в Log.js, как:
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_1} />
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_2} />
И чтобы потом, в LogComponent сделать что-то вроде:
<List style={style}> ... </List>
Я также пытался использовать что-то вроде
<List className={list_1}> ... </List>
Но ничего из того, что я пробовал, не работает...
Log.js
import React from 'react'
import Typography from '@material-ui/core/Typography'
import { withStyles } from '@material-ui/core/styles'
import LogComponent from './LogComponent'
const styles = theme => ({
title: {
padding: theme.spacing.unit*1.5,
},
list_1: {
},
list_2: {
width: "300px"
},
listContainer: {
flexGrow: 1,
minHeight: 0,
overflow: 'auto'
},
})
const Log = ({classes, log}) => {
const page_1 = log[0];
const page_2 = log[1];
return (
<div>
<Typography className={classes.title} color="textSecondary" key={1}>
Example Log
</Typography>
<div className={classes.listContainer} key={2}>
<LogComponent heading={'Page 1'} lines={page_1} />
<LogComponent heading={'Page 2'} lines={page_2} />
</div>
</div>
export default withStyles(styles)(Log)
LogComponent.js
import React from 'react'
import Typography from '@material-ui/core/Typography'
import { withStyles } from '@material-ui/core/styles'
import { List, ListItem, ListItemText } from '@material-ui/core';
const styles = theme => ({
title: {
padding: theme.spacing.unit*1.5,
},
}
const LogComponent = ({classes, list_class, heading, lines}) => {
return (
<div className={classes.root}>
<Typography className={classes.title} color="textSecondary" key={1}>
{heading}
</Typography>
<div>
<List dense>
{[...lines[0]].map(e =>
<ListItem><ListItemText primary={e} /></ListItem>
)}
</List>
</div>
</div>
)
}
export default withStyles(styles)(LogComponent)
1 ответ
Здесь вы отправляете стили как prop
в LogComponent
Вот почему он не будет применяться как стили к тому компоненту, который вы создали. Атрибут style предназначен для тегов HTML, а в material-ui вы также можете передавать стили в компонент-оболочку.
В вашем случае вы можете получить стили внутри вашего LogComponent
как показано ниже:
Отправьте стили в качестве опоры, как вы упомянули в вопросе
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_1} />
Теперь вы можете получить к нему доступ из реквизита,
// right below get the style
const LogComponent = ({classes, list_class, heading, lines, style}) => {
return (
<div className={classes.root} style={style}> // Look style attribute added, style(value) is from props
<Typography className={classes.title} color="textSecondary" key={1}>
{heading}
</Typography>
<div>
<List dense>
{[...lines[0]].map(e =>
<ListItem><ListItemText primary={e} /></ListItem>
)}
</List>
</div>
</div>
)
}