배열에서 특정 요소의 색상을 변경하는 방법
Aug 21 2020
React를 사용하여 정렬 시각화 도우미를 만들려고합니다. 지금은 BubbleSort를 구현하고 있습니다. 프로그램은 다음과 같습니다.

코드는 다음과 같습니다.
class Sorter extends Component {
state = {
array: [100,4,214,55,11,22,10,33],
color: "blueviolet",
}
bubblesorter = async () => {
let arr = this.state.array
var len = arr.length,
i, j, stop;
for (i=0; i < len; i++){
for (j=0, stop=len-i; j < stop; j++){
if (arr[j] > arr[j+1]){
swap(arr, j, j+1);
}
await new Promise(resolve => setTimeout(resolve, 100));
this.setState({array:arr})
}
}
}
render() {
const array = this.state.array
return (
<div>
<h1>This is a sorter</h1>
<div className="container">
{array.map((value, id) => (
<span>
<div className="bar" key={id} style={{height: value+"px", backgroundColor: this.state.color}} >
</div>
</span>
))}
</div>
<button onClick={this.bubblesorter}>Sort</button>
</div>
)
}
정렬 기능이 올바르게 작동합니다. 하지만 막대의 색상을 변경하고 싶습니다 (비교되는 배열 요소). 누군가 이것을 구현하는 데 사용할 수있는 논리를 도울 수 있습니까? 감사합니다
답변
1 yash Aug 21 2020 at 15:05
colors
배열을 만들고 변경된 색상 만 업데이트 할 수 있습니다 .
class Sorter extends Component {
state = {
array: [100, 4, 214, 55, 11, 22, 10, 33],
colors: Array(8).fill('blueviolet'), // Array of colors for each bar
};
bubblesorter = async () => {
...
await new Promise((resolve) => setTimeout(resolve, 100));
// Set different item's color as `red`
const colors = arr.map((item, index) => (this.state.array[index] === item ? 'blueviolet' : 'red'));
this.setState({ array: arr, colors });
}
}
};
render() {
const { array, colors } = this.state;
return (
<div>
<h1>This is a sorter</h1>
<div className='container'>
{array.map((value, id) => (
<span>
<div
className='bar'
key={id}
// <- Use the color at the same index of the item
style={{ height: value + 'px', backgroundColor: colors[id] }}
></div>
</span>
))}
</div>
<button onClick={this.bubblesorter}>Sort</button>
</div>
);
}
}
Dev5 Aug 21 2020 at 17:53
이것을 시도했습니다 ... 작동하지만 현대 자바 스크립트를 사용하여 개선 할 수 있습니다 (익숙하지 않음, 제안 환영)
class Sorter extends Component {
state = {
array: [],
colors: Array(8).fill('blueviolet'),
}
bubblesorter = async () => {
...
await new Promise(resolve => setTimeout(resolve, 1000));
const colors = []
for (let k=0; k<8; k++) {
let color = k==j || k==j+1 ? 'red':'blueviolet'
colors[k] = color
}
// console.log(colors)
this.setState({ array: arr, colors: colors });
}
}
render()
{
// const array = this.state.array
const { array, colors } = this.state;
// console.log(array)
return (
<div>
<h1>This is a sorter</h1>
<div className="container">
{array.map((value, id) => (
<span>
<div
className="bar"
key={id}
style={{ height: value + 'px', backgroundColor: colors[id]
}} >
</div>
{/* <span>{value}</span> */}
</span>
))}
</div>
<button onClick={this.bubblesorter}>Sort</button>
</div>
)
}
}