我刚开始使用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;
}
您可能已经知道这将背景图像应用于所有列表项(正方形)。所以,我只是无法找到解决这个问题的方法。任何帮助和批评将不胜感激。谢谢!
这可以通过单元属性className上的CSS切换类完全完成。注意风格也需要一个物体喂食。包含短划线(IE:background-image)的属性名称也需要在camelcase中转换(IE:backgroundImage)
<MyComponent style={{ backgroundImage: 'url: http://myurl.jpg' }} />
正如你刚刚开始做出反应一样,我只会告诉你该怎么做,这样你才能真正实现并学习一些。
style
,例如style={someClass}
。这很简单,但会为所有正方形单独显示相同的背景图像。
<li>
。例如.. <li style={{backgroundImage: 'some/loc/file.format'}} className={holderClass}>
有了这个,您实际上可以将自定义图像发送到每个方块(从反应
state
存储和检索)