繁体   English   中英

样式列表项onMouseOver-React.js

[英]Style list item onMouseOver - React.js

我刚开始使用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;
}

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

这完全可以通过CSS切换单元格属性className上的类来完成。 注意样式还需要一个对象。 同样,包含破折号(IE:background-image)的属性名称也需要在驼峰格式(IE:backgroundImage)中进行转换。

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

在您刚开始做出反应时,我将告诉您该怎么做,以便您可以实际实施并学习一些知识。

  1. 创建一个css类,该类的背景图像集的尺寸类似于正方形。 将鼠标悬停在正方形上时,只需将类传递给style style={someClass}

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


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

这样,您实际上可以将自定义图像发送到每个正方形(从react state存储和检索)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM