首页 > 解决方案 > 无法在 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}
        }
    });

标签: reactjsmaterial-ui

解决方案


  1. makeStyles 更适合用于功能组件,而不是类组件。

  2. 在函数组件中使用 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

推荐阅读