I just started with React and I am currently building a Tic Tac Toe game for learning purposes. 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:
event.target.style = <bacgroundImageUrl>
which of course is an anti-pattern in 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. 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)
<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={someClass}
. This is simple and but will have same background image displayed for all squares, individually.
<li>
through style with the created class. 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
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.