基于@CodingYourLife的解决方案和这个问题的主要主题,我根据自己的两个需求制作了组件的版本。我将react-router-dom
的行为与<A>
HTML标签的本地行为相结合。
Link
组件的文件
- index.tsx
- types.ts
- styles.ts
index.tsx
(如下)
import * as React from 'react';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core';
import { Link as RouterLink } from 'react-router-dom';
import styles from './styles';
import { IProps } from './types';
class Link extends React.PureComponent<IProps> {
render(): JSX.Element {
const {
classes,
href,
children,
...routerLinkProps
} = this.props;
if (typeof href === 'string') {
return (
<a href={href}>
<Typography
className={classes.value}
>
{children}
</Typography>
</a>
);
}
return (
<RouterLink
to={'#'} // for <a> link default value because it's required by its lib
{...routerLinkProps}
>
<Typography
className={classes.value}
>
{children}
</Typography>
</RouterLink>
);
}
}
export default withStyles(styles)(Link);
styles.ts
(如下)
import { Theme, createStyles } from '@material-ui/core';
export default (theme: Theme): ReturnType<typeof createStyles> => createStyles({
value: {
display: 'inline-block',
color: theme.palette.secondary.main,
fontWeight: 500,
'&:hover': {
textDecoration: 'underline',
},
},
});
types.ts
(如下)
import {
WithStyles,
} from '@material-ui/core';
import { LinkProps } from 'react-router-dom';
import styles from './styles';
export type IProps = WithStyles<typeof styles> & Partial<LinkProps> & {
href?: string;
};
使用的库:material-ui
<a />
)是正确的。对于应用一些样式到该元素本身(而不是可能应用于底层button
元素的样式),是否存在问题? - Drew Reese