Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

javascript - React shared state: highlight which component is selected

I'm pretty new to react, and am working on a big existing codebase.

This website has a list of components (square blocks), and when I press on one of them (say Block1), I want that one (Block1) to change from white to a blue background color. If I press on another block (say Block3), then I want the previous block (Block1) to change back to white, and the block I just selected (Block3) to change to blue.

I have a List file with a functional component that returns a list of blocks, like so:

ItemList() {
   return ({edge.map() => return <Block />}) //this basically returns like 10 Blocks
}

Block Component File

Block() {
   return (<div> blah blah </div>)
}

What's the easiest way for me to do this? I currently have a state inside of the Block() component, but this isn't letting me update when I press on another block, and want this block to change back.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. State selectedBlock should be stored in ItemList and passed down to the blocks
  2. ItemList should send a function setSelectedBlock to the children which will be called inside them inside the onClick.
  3. Each block will receive a key from the map function
  4. Inside the block check bgColor = props.key === props.selectedBlock ? 'blue' : 'white'
  5. Apply the color with inline CSS
  6. Feel free to ask any questions on this!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...