gpt4 book ai didi

html - 动态更新css类属性

转载 作者:行者123 更新时间:2023-12-04 07:14:07 25 4
gpt4 key购买 nike

我有以下 CSS 并在 reactJS 中进行标记,并希望动态更新背景属性。假设在少数情况下,它应该是红色,少数情况下应该是黑色。

   goodOne: {
position: 'relative',
'&:before': {
position: 'absolute',
background: 'This value needs to be filled dynamically',
borderRadius: '50%'
}
}

<div className = {classes.goodOne}>Hello world</div>
我怎样才能做到这一点?

最佳答案

ReactJSS documentation

import React from 'react'
import {createUseStyles} from 'react-jss'

const useStyles = createUseStyles({
myButton: {
padding: props => props.spacing
},
myLabel: props => ({
display: 'block',
color: props.labelColor,
fontWeight: props.fontWeight,
fontStyle: props.fontStyle
})
})

const Button = ({children, ...props}) => {
const classes = useStyles(props)
return (
<button className={classes.myButton}>
<span className={classes.myLabel}>{children}</span>
</button>
)
}

Button.defaultProps = {
spacing: 10,
fontWeight: 'bold',
labelColor: 'red'
}

const App = () => <Button fontStyle="italic">Submit</Button>

Example (Codesandbox)

import React from 'react';
import { ThemeProvider, createUseStyles } from 'react-jss';

const useStyles = createUseStyles((theme) => ({
background: {
color: theme.color,
background: ({ background }) => background,
width: 300,
height: 300
}
}));

function MyComponent() {
const [background, setBackground] = React.useState('black');

const classes = useStyles({
background: background
});

return (
<React.Fragment>
<div className={classes.background}>Hello, world</div>

<button onClick={() => setBackground('red')}>Change to red</button>
<button onClick={() => setBackground('black')}>Change to black</button>
</React.Fragment>
);
}

function App() {
const theme = {
color: 'green'
};

return (
<ThemeProvider theme={theme}>
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>

<MyComponent />
</ThemeProvider>
);
}

关于html - 动态更新css类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68890354/

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