我有一组组件,我希望每个组件都显示我定义的AppBar,如下所示:
const FireAppBar = (props) => {
const { classes } = props;
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
{props.route &&
<Link to={{ pathname: props.route }} style={{textDecoration: 'none'}}>
<IconButton className={classes.menuButton} color="contrast">
<ArrowBackIcon/>
</IconButton>
</Link>}
<Typography type="title" color="inherit" className={classes.flex}>
{props.title || ''}
</Typography>
{props.rightIcon
? props.rightIcon
: <Avatar className={classes.orangeAvatar}>M</Avatar>}
</Toolbar>
</AppBar>
</div>
);
}
我想根据正在呈现的组件自定义App Bar外观。即如果传递route prop
,我想渲染一个后退按钮。
我目前这样做的方法是在我的每个组件中专门包含AppBar,例如:
class Entries extends Component {
constructor() {
super();
this.state = {
entries: [],
jobId: ''
};
render() {
const { classes } = this.props;
return (
<div className="App">
<AppBar title={`Entries for ${this.state.jobId}`} route={"/jobs"}/>
<EntriesTable entries={this.state.entries}/>
<Link to={{ pathname: `/createEntry/${this.jobKey}` }}>
<Button fab color="primary" aria-label="add" className={classes.button}>
<AddIcon />
</Button>
</Link>
</div>
);
}
有没有办法在顶级App.js组件中包含App Bar,而不是在每个组件中指定它?
class App extends Component {
componentWillReceiveProps(nextProps) {
console.log(nextProps.location)
}
render() {
const { classes } = this.props;
return (
<Router>
<div className="App">
<main>
<Route exact path="/" component={Jobs} />
<Route path="/jobs" component={Jobs} />
<Route path="/entries/:id" component={Entries} />
<Route path="/createEntry/:id" component={CreateEntry} />
</main>
</div>
</Router>
);
}
}
export default withStyles(styles, { withTheme: true })(App);