React添加styled-components样式后按钮功能失效及makeStyles使用咨询
问题1:styled-components封装按钮后跳转失效的解决
跳转失效的根因:你封装TriggerButton时用的是styled.button,生成的是原生<button>标签,它本身不支持Material UI Button 组件的component、to等定制属性,Link组件的跳转逻辑无法被注入,自然无法跳转。
解决方法很简单,把styled的封装目标换成你已经引入的MUI Button 组件即可:
// 把原来的styled.button改成styled(Button) const TriggerButton = styled(Button)` cursor: pointer; outline: none; position: relative; z-index: 3; background: transparent; border-color: #664e96; border-style: solid; border-width: 2px; border-radius: 22px; padding: 10px 25px; font-size: 11px; text-transform: uppercase; transition: all 0.2s linear; &:hover { background: #664e96; color: #fff; } `;
改完后component={Link}、startIcon等属性都会被MUI Button正常解析,跳转功能即可恢复。同时提醒你原来把props存在state里的写法是多余的,直接用this.props即可,存state反而会导致props更新时不同步的问题。
问题2:接入makeStyles的实现方案
makeStyles是MUI提供的Hooks API,仅能在函数组件中使用。如果你的组件可以改成函数组件,直接用makeStyles定义样式即可;如果要保留类组件写法,推荐使用MUI配套的withStyles高阶组件实现样式注入。
方案1:改为函数组件使用makeStyles
import React from "react"; import Button from "@material-ui/core/Button"; import AddIcon from "@material-ui/icons/Add"; import { Link } from "react-router-dom"; import { makeStyles } from "@material-ui/core/styles"; // 用makeStyles定义样式 const useStyles = makeStyles({ triggerBtn: { cursor: "pointer", outline: "none", position: "relative", zIndex: 3, background: "transparent", borderColor: "#664e96", borderStyle: "solid", borderWidth: "2px", borderRadius: "22px", padding: "10px 25px", fontSize: "11px", textTransform: "uppercase", transition: "all 0.2s linear", "&:hover": { background: "#664e96", color: "#fff", } } }) export default function AddTriggerButton(props) { const classes = useStyles(); return ( <div> <Button className={classes.triggerBtn} component={Link} to={{ pathname: "/_triggers/create", data: { eid: props.record.id }, }} startIcon={<AddIcon />} > 新建触发器 </Button> </div> ); }
方案2:保留类组件使用withStyles
import React from "react"; import Button from "@material-ui/core/Button"; import AddIcon from "@material-ui/icons/Add"; import { Link } from "react-router-dom"; import { withStyles } from "@material-ui/core/styles"; // 定义样式对象 const styles = { triggerBtn: { cursor: "pointer", outline: "none", position: "relative", zIndex: 3, background: "transparent", borderColor: "#664e96", borderStyle: "solid", borderWidth: "2px", borderRadius: "22px", padding: "10px 25px", fontSize: "11px", textTransform: "uppercase", transition: "all 0.2s linear", "&:hover": { background: "#664e96", color: "#fff", } } } class AddTriggerButton extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } render() { const { classes, record } = this.props; return ( <div> <Button className={classes.triggerBtn} component={Link} to={{ pathname: "/_triggers/create", data: { eid: record.id }, }} startIcon={<AddIcon />} > 新建触发器 </Button> </div> ); } } // 用withStyles包裹组件导出 export default withStyles(styles)(AddTriggerButton);
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

