首先,这段代码对我有用,但我想知道是否有任何问题。
我尝试改变一个被多次调用的组件的状态,这比我在 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>
)
}
}
按钮.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 = (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 })
}