gpt4 book ai didi

javascript - 将条件样式应用于 React 中的组件 - 内联 CSS

转载 作者:行者123 更新时间:2023-12-02 02:53:55 26 4
gpt4 key购买 nike

我正在尝试根据某些按钮是否“事件”以及是否将鼠标悬停在它们上来设置它们的样式。

它在某种程度上有效,但是,它的行为方式我并不完全理解。

如何根据组件的状态以及用户行为将条件样式应用于组件?

我在这个SANDBOX中有一个例子

主 JS 文件复制到这里:

demo.js

import React from "react";
import PropTypes from "prop-types";
//import { makeStyles } from "@material-ui/core/styles";
import { withStyles } from "@material-ui/styles";
import { Button } from "@material-ui/core";

const useStyles = theme => ({
root: {
backgroundColor: theme.palette.secondary.paper,
width: 500
},
pageButton: {
backgroundColor: "black",
color: "blue",
width: 30,
minWidth: 20,
"&:hover": {
backgroundColor: "green"
}
},
normalButton: {
width: 30,
minWidth: 20,
backgroundColour: "red"
}
});

class Feature extends React.Component {
constructor(props) {
super(props);
this.state = { currentPage: 0 };
}
handleClick(page) {
this.setState({ currentPage: page });
}

fetchPageNumbers() {
return [1, 2, 3];
}
render() {
const classes = this.props.classes;
return (
<div className={classes.root}>
{this.fetchPageNumbers().map((page, index) => {
return (
<div>
<Button
onClick={() => this.handleClick(page)}
key={page}
className={
this.state.currentPage === page
? classes.pageButton
: classes.normalbutton
}
>
{page}
</Button>

<Button
onClick={() => {}}
key={page * 20}
className={classes.normalButton}
>
{page * 20}
</Button>
</div>
);
})}
</div>
);
}
}

Feature.propTypes = {
classes: PropTypes.object.isRequired
};

export default withStyles(useStyles)(Feature);

有两行。第二行的风格很好。仅当单击按钮时才会粘附第一行。我希望能够根据当前按钮是否处于事件状态(即状态==按钮编号)以及用户是否将鼠标悬停在任何按钮上来设置状态。

最佳答案

How do I apply a conditional style to a component, based on its state, as well as based on user behavior?


基于用户行为的条件样式

我猜你当前的需求是在徘徊的时候。

"&:hover": {
// Hover styles
}

对于基于 params(props) 的条件样式

withStyles 无权访问这些属性。


但是有多种解决方案

1.使用injectSheet HOC

请注意,代码中的 useStyles 实际上不是钩子(Hook)

const styles = props => ({
root: {
width: props.size === 'big' ? '100px' : '20px'
}
})

const styles = {
root: {
width: props => props.size === 'big' ? '100px' : '20px'
}
}

const CustomFeature = ({size, classes}) => <Feature className={classes.root} />;

export default withStyles(styles)(CustomFeature);

2.使用带有参数的样式钩子(Hook)(用于功能组件)

import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(theme => ({
root: {
width: props => props .size === "big" ? "100px" : "20px"
}
}));

const classes = useStyles();

import { makeStyles } from "@material-ui/core/styles";
const useStyles = params =>
makeStyles(theme => ({
root: {
width: params.size === "big" ? "100px" : "20px"
}
}));

const classes = useStyles(whateverParamsYouWant)();

关于javascript - 将条件样式应用于 React 中的组件 - 内联 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61477763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com