[英]Style list item onMouseOver - React.js
I just started with React and I am currently building a Tic Tac Toe game for learning purposes. 我刚开始使用React,目前正在构建一个Tic Tac Toe游戏,用于学习。 When the user hovers over a square which is a list item, I want that square to have a background image.
当用户将鼠标悬停在作为列表项的正方形上时,我希望该正方形具有背景图像。 So far I am able to do it only if I manipulate the DOM directly like this:
到目前为止,仅当我像这样直接操作DOM时,我才能这样做:
event.target.style = <bacgroundImageUrl>
which of course is an anti-pattern in React 当然这是React中的反模式
Here is what my state looks like: 这是我的状态:
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
}
This is what's inside my render function: 这是我的渲染函数内部的内容:
<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>
And also the component: 还有组件:
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;
}
As you may already know this applies background image to all list items(squares). 您可能已经知道,这会将背景图像应用于所有列表项(正方形)。 So, I am just not able to find a way of solving this.
因此,我只是找不到解决此问题的方法。 Any help and criticism will be greatly appreciated.
任何帮助和批评将不胜感激。 Thanks!
谢谢!
This can be done entirely by CSS switching class on property className of your cell. 这完全可以通过CSS切换单元格属性className上的类来完成。 Note also style need a object to be fed.
注意样式还需要一个对象。 Also property name that contain a dash (IE: background-image) need to be converted in camelcase (IE: backgroundImage)
同样,包含破折号(IE:background-image)的属性名称也需要在驼峰格式(IE:backgroundImage)中进行转换。
<MyComponent style={{ backgroundImage: 'url: http://myurl.jpg' }} />
As you have just begun with react, I will just tell you what to do, so that you could actually implement it and learn some. 在您刚开始做出反应时,我将告诉您该怎么做,以便您可以实际实施并学习一些知识。
style
eg. style
。 style={someClass}
. style={someClass}
。 This is simple and but will have same background image displayed for all squares, individually.
这很简单,但是将为所有正方形单独显示相同的背景图像。
<li>
through style with the created class. <li>
。 eg. <li style={{backgroundImage: 'some/loc/file.format'}} className={holderClass}>
With this, you can actually send custom image to each square (stored and retrieved from react
state
)这样,您实际上可以将自定义图像发送到每个正方形(从react
state
存储和检索)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.