reactjs - 无法在 makeStyle 中使用“this”
问题描述
我想根据我的道具创建动态背景图像。因此,为此我想制作一种反应样式并将其存储在我的图片中,state
但我无法this.state.pictures
在其中使用,我不知道为什么。
class DisplayArtist extends Component {
state = {
name : this.props.Info.artists.items[0].name,
followers: this.props.Info.artists.items[0].followers.total,
genres: this.props.Info.artists.items[0].genres,
picture: this.props.Info.artists.items[0].images[0]
}
useStyles = makeStyles({
root: {
backgroundImage={this.state.pictures}
}
});
解决方案
makeStyles 更适合用于功能组件,而不是类组件。
在函数组件中使用 makeStyes 会导致在每次渲染时重新创建样式。我不建议这样做。
推荐的方法是对动态背景图像使用内联样式
e.g. style={{ backgroundImage: artist.images[0] }}
转换为功能组件
const DisplayArtist = (props) => {
const [ artist, setArtist ] = useState(null);
useEffect(() => {
//do your own checks on the props here.
const { name, total, genres, images } = props.Info.artists.items[0]
setArtist({name, total, genres, images});
},[props])
return ( <div style={{ width: '200px', height:'200px', backgroundImage: artist.images[0] }} /> )
}
export default DisplayArtist
推荐阅读
- javascript - 加载页面时如何打开模块/画布?
- python - 如何使用 scikit-learn 在 python 中聚类后向气团轨迹?
- vba - VBA 中的幻灯片计数变量 - Powerpoint
- node.js - Bootstrap 列在 IE 11 中的行为不符合预期
- autodesk-forge - 是否有 Autodesk Forge API 可用于管理 Autodesk BIM 360 Docs 中的审批工作流?
- flutter - 在颤振中从 QuerySnapshot 中提取数据
- react-native - 反应原生的 iframe
- javascript - discord.js bot 嵌入消息图像未显示
- php - 颤振,我的 DataTable 和 php Json 输出问题......无法解决
- string - 如何在飞镖中从右到特定字符获取所有字符