问题描述
我需要以如下所示的方式将动态值传递给线性渐变。我该怎么做?我尝试在cssinjss网站上实现动态值的小示例,但没有成功。
const useStyles = createUseStyles({
card:{
background: 'linear-gradient(to top,orange,rgb(to top,255,props.green,0))',width: '200px',height: '240px',margin: '50px',display: "flex",flexDirection: 'column',justifyContent: 'space-around',alignItems: 'center',color: 'white',fontFamily: 'arial',padding: 6,borderRadius: 15,composes: 'shadow'
}
});
const WeatherCard = (props) => {
const classes = useStyles(props);
return (
<div>
<div className={classes.card}>
<Location />
<Icon />
<Tempature />
</div>
</div>
);
};
WeatherCard.defaultProps = {
green: 125
};
解决方法
您的代码是正确的,只是缺少使用变量告诉回调变量props
的回调,请尝试以下操作:
参见:https://cssinjs.org/react-jss/?v=v10.4.0#dynamic-values
const useStyles = createUseStyles({
card:{
background: props => `linear-gradient(to top,orange,rgb(to top,255,${props.green},0))`,width: '200px',height: '240px',margin: '50px',display: "flex",flexDirection: 'column',justifyContent: 'space-around',alignItems: 'center',color: 'white',fontFamily: 'arial',padding: 6,borderRadius: 15,composes: 'shadow'
}
});
const WeatherCard = (props) => {
const classes = useStyles({...props});
return (
<div>
<div className={classes.card}>
<Location />
<Icon />
<Tempature />
</div>
</div>
);
};
,
如果只是放置动态值的地方,我会对其进行内联样式设置。我知道事情必须“完美”,但是内联样式完全合法,我也将使用模板文字。
因此,假设我有一个从中取道具的组件。
function foo ({ green }) {
return <div style='background:${green}'></div>
}
我使用了大括号,因此不需要props关键字,因为它理解我正在尝试获取变量名。