Отключите, этот код работает для меня, но мне было интересно, если что-то не так.
Я попытался поэкспериментировать с изменением состояния одного компонента, который вызывается несколько раз, и это было сложнее, чем я понял вReact.Мне удалось это сделать, но я чувствую, что делаю плохую практику в классе toggleClass.Если это хорошая практика, но есть лучший способ сделать это, или если в этом нет ничего плохого, этот нуб хотел бы знать.
ButtonContainer.js
import React from 'react'
import Button from './Button'
export default class ButtonContainer extends React.Component {
state = {
colors: ['red', 'blue', 'green'],
active: true
}
toggleClass = (color, id) => {
let colors = [...this.state.colors]
colors.map((newColor, index) => {
if (id === index) {
let copy = { ...colors[index] }
if (color === 'not') {
if (index === 0) {
copy = 'red'
} else if (index === 1) {
copy = 'blue'
} else if (index === 2) {
copy = 'green'
}
} else {
copy = 'not'
}
colors[index] = copy
this.setState({ colors })
}
})
}
render() {
return (
<div className='button-container'>
{this.state.colors.map((color, index) =>
<Button
toggleClass={this.toggleClass}
key={index}
id={index}
name={color}
/>
)}
</div>
)
}
}
Button.js
import React from 'react'
const Button = (props) => (
<button
className={`button-component ${props.name}`}
onClick={() => props.toggleClass(props.name, props.id)}
>
{props.name}
</button>
)
export default Button
CSS
.button-container {
margin: 10rem auto;
text-align: center;
}
.button-component {
padding: 4rem;
margin: 0 2rem;
}
.red {
background: red;
}
.blue {
background: blue;
}
.green {
background: green;
}
.not {
background: none;
}
- ОБНОВЛЕНИЕ -
Улучшен toggleClass
toggleClass = (color, id) => {
let colors = [...this.state.colors]
const newColors = colors.map((newColor, index) => {
if (id === index) {
const copyMap = { 0: 'red', 1: 'blue', 2: 'green' }
const copy = color === 'not' ? copyMap[index] : 'not'
return copy
} else {
return newColor
}
})
this.setState({ colors: newColors })
}