样式列表项onMouseOver - React.js

问题描述 投票:0回答:2

我刚开始使用React,我目前正在构建一个用于学习目的的Tic Tac Toe游戏。当用户将鼠标悬停在作为列表项的正方形上时,我希望该正方形具有背景图像。到目前为止,只有当我像这样直接操作DOM时,我才能做到这一点:

event.target.style = <bacgroundImageUrl>

这当然是React中的反模式

这是我的州的样子:

state = {
 gameInProgress: true,
 player1Active: false,
 player2Active: false,
 board: [1, 2, 3, 4, 5, 6, 7, 8, 9],
 squareHovered: false,
 player1Winner: false,
 player2Winner: false,
 player1BgImg: null,
 player2BgImg: null,
 tie: false,
 winner: false
}

这就是我的渲染函数中的内容:

<Board>
<Squares
   bg={
       this.state.player1Active
           ? this.state.player1BgImg
       :this.state.player2Active
           ? this.state.player2BgImg
       : null}
   hovered={(event) => this.hoverOverSquare(event)}
   notHovered={(event) => this.notHoverOverSquare(event)}
   clicked={(event) => this.fillSquare(event,
       this.state.player1Active
           ? this.playersData.player1Sign
       : this.state.player2Active
           ? this.playersData.player2Sign
       : null
    )}/>
</Board>

还有组件:

const Squares = (props) => {
let squares = [];

for(let i = 1; i < 10; i++){
    squares.push(
        <li
            id={i}
            key={i}
            style={props.bg}
            onClick={props.clicked}
            onMouseLeave={props.notHovered}
            onMouseOver={props.hovered}
            className="box">
        </li>
    )
}

 return squares;
}

您可能已经知道这将背景图像应用于所有列表项(正方形)。所以,我只是无法找到解决这个问题的方法。任何帮助和批评将不胜感激。谢谢!

javascript reactjs
2个回答
0
投票

这可以通过单元属性className上的CSS切换类完全完成。注意风格也需要一个物体喂食。包含短划线(IE:background-image)的属性名称也需要在camelcase中转换(IE:backgroundImage)

<MyComponent style={{ backgroundImage: 'url: http://myurl.jpg' }} />

0
投票

正如你刚刚开始做出反应一样,我只会告诉你该怎么做,这样你才能真正实现并学习一些。

  1. 创建具有背景图像集的css类,其尺寸类似于正方形的尺寸。在徘徊在广场上只需将课程传递给style,例如style={someClass}

这很简单,但会为所有正方形单独显示相同的背景图像。


  1. 创建一个类似上面的类,除了,不要提到背景图像。您可以在状态下设置背景图像,并通过创建的类的样式将其传递给<li>。例如.. <li style={{backgroundImage: 'some/loc/file.format'}} className={holderClass}>

有了这个,您实际上可以将自定义图像发送到每个方块(从反应state存储和检索)

© www.soinside.com 2019 - 2024. All rights reserved.