- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在构建一个排序算法可视化工具。这些项目中的每一项都是 div
,backgroundColor
设置为白色。
当算法运行时,他将 backgroundColor
设置为橙色以显示哪些项目已更改。
但是当我使用 setState()
重置数组时,问题发生了,因为 react 重新渲染新数组非常好,但他从未将背景颜色渲染回白色。
这是我的组件:
import React from 'react'
import './SortingVisualizer.css'
import InsertionSort from '../SortingAlgorithms/InsertionSort'
const NORMAL_COLOR = 'white';
const CHANGED_COLOR = 'red';
const AFTER_CHANGE_COLOR = 'orange';
export default class SortingVisualizer extends React.Component{
constructor(props){
super(props);
this.state = {
arrayToSort: []
};
}
componentDidMount(){
this.resetArray();
}
resetArray(){
const arrayToSort = [];
for (let i = 0; i < 200; i++) {
arrayToSort.push(this.RandomIntBetweenRange(5, 1000));
}
this.setState({ arrayToSort });
}
insertionSort(){
let sortedArrayAnim = InsertionSort(this.state.arrayToSort);
let arrayToSort = this.state.arrayToSort;
let arrayBars = document.getElementsByClassName('array-item');
let arrayBarsWithColorChanged = [];
//loop through all the animations
for (let index = 0; index < sortedArrayAnim.length; index++) {
const [i,j] = sortedArrayAnim[index];
//setTimeout(() => {
//set changed colors back to normal
if(index !== 0){
arrayBarsWithColorChanged.forEach((element, index) => {
arrayBars[element].style.backgroundColor = AFTER_CHANGE_COLOR;
});
arrayBarsWithColorChanged = [];
}
let temp = arrayToSort[i];
//change array
arrayToSort[i] = arrayToSort[j];
arrayToSort[j] = temp;
//change div bar colors, unl
if(index != sortedArrayAnim.length - 1){
arrayBars[i].style.backgroundColor = CHANGED_COLOR;
arrayBars[j].style.backgroundColor = CHANGED_COLOR;
arrayBarsWithColorChanged.push(i);
arrayBarsWithColorChanged.push(j);
}
this.setState({ arrayToSort })
//}, 10);
}
}
render() {
const {arrayToSort} = this.state;
return (
<div className="main-div">
{arrayToSort.map((value, idx) => (
<div className="array-item" key={idx} style={{height: value, backgroundColor: 'white'}}>
</div>
))}
<button onClick={() => this.resetArray()}>Generate new array</button>
<button onClick={() => this.insertionSort()}>Insertion Sort</button>
</ div>
);
}
RandomIntBetweenRange(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
最佳答案
在 React 中,您不直接操作 DOM,也不改变状态(例如 arrayToSort[i] = arrayToSort[j]
)。您更改模型(状态、 Prop ), View 也会相应更改。
因此,在您的情况下,您需要在状态中包含列值数组 (arrayToSort
)、要交换的对数组 (sortedArrayAnim
),以及一组先前更改的值 (prevChanged
)。每当发生变化时, View 都会根据这些状态值进行更新。
演示(见代码注释):
const NORMAL_COLOR = 'white';
const CHANGED_COLOR = 'red';
const AFTER_CHANGE_COLOR = 'orange';
/** this function return the color **/
const getColor = (idx, prevChanged, [current]) => {
if(current && current.includes(idx)) return CHANGED_COLOR; // if it's in current changed pair [i, j]
if(prevChanged.has(idx)) return AFTER_CHANGE_COLOR; // if it was changed before
return NORMAL_COLOR;
}
class SortingVisualizer extends React.Component {
state = {
arrayToSort: [],
sortedArrayAnim: [],
prevChanged: new Set()
};
timeout = null;
componentDidMount() {
this.resetArray();
}
resetArray = () => {
clearTimeout(this.timeout);
const arrayToSort = [];
for (let i = 0; i < 50; i++) {
arrayToSort.push(this.RandomIntBetweenRange(1, 100));
}
this.setState({
arrayToSort,
sortedArrayAnim: [],
prevChanged: new Set()
});
}
animate = (sortedArrayAnim) => {
this.setState(
({
prevChanged,
arrayToSort
}) => {
if(!sortedArrayAnim.length) return { sortedArrayAnim };
const [current] = sortedArrayAnim;
const newArrayToSort = [...arrayToSort]; // clone newArrayToSort
/** flip the values according to current change [i, j] **/
newArrayToSort[current[0]] = arrayToSort[current[1]];
newArrayToSort[current[1]] = arrayToSort[current[0]];
return ({
arrayToSort: newArrayToSort,
sortedArrayAnim,
prevChanged: new Set([...prevChanged, ...current]) // add changed items to the Set
});
},
() => { // when state change is done
const { sortedArrayAnim } = this.state;
// if there are more items to change wait and call animate again
if(sortedArrayAnim.length) {
this.timeout = setTimeout(() => this.animate(sortedArrayAnim.slice(1)), 1000);
}
}
);
}
insertionSort = () => {
const sortedArrayAnim = [[1, 5], [10, 15], [20, 13], [17, 48], [20, 13], [45, 17]]; // InsertionSort(this.state.arrayToSort); // I've used a dummy array
this.animate(sortedArrayAnim);
}
render() {
const { arrayToSort, sortedArrayAnim, prevChanged } = this.state;
return (
<div className="main-div">
{arrayToSort.map((value, idx) => (
<div className="array-item" key={idx} style={{
height: `${value}vh`,
backgroundColor: getColor(idx, prevChanged, sortedArrayAnim)
}}>
</div>
))}
<button onClick={this.resetArray}>Generate new array</button>
<button onClick={this.insertionSort}>Insertion Sort</button>
</ div>
);
}
RandomIntBetweenRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
ReactDOM.render(
<SortingVisualizer />,
root
);
.main-div {
display: flex;
align-items: flex-end;
justify-content: space-between;
background: black;
height: 100vh;
padding: 1vmax 1vmax 0 ;
box-sizing: border-box;
}
.array-item {
width: 1vw;
transition: height 0.3s;
}
button {
align-self: flex-start;
}
body {
margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
关于javascript - backgroundColor 不会重新渲染 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58530676/
我想使用 JavaScript 将 #Content.backgroundColor 更改为 elem.backgroundColor。 这里是 HTML 代码: Btn1 Btn2 Btn3 这是
@implementation AVSuperView - (AVSuperView*)initWithFrame:(CGRect)frame{ if (self = [super initW
这两行 Swift 代码在功能上有区别吗? self.button.layer.backgroundColor = UIColor.whiteColor().CGColor 和 self.button
我正在尝试学习 React.JS,但有些事情让我大吃一惊。 我有这个标题组件: class Header extends Component { render() { return ;
我正在尝试学习 React.JS,但有些事情让我大吃一惊。 我有这个标题组件: class Header extends Component { render() { return ;
我正在尝试为事件添加背景颜色,但没有运气。 $('#calendar').fullCalendar('renderEvent', { id: 1, title: 'hello', start: sel
这是在iOS 9中。我无法设置SKView的背景颜色,它始终以默认的灰色呈现。有没有解决的办法? let frame = CGRect(x: 0, y: 0, width: 200, height:
我正在创建一个 SWRevealView Controller ,每当我使用 self.view.backgroundColor 或实例化一个新的 View Controller 并使用 UIView
我正在尝试向使用 backgroundColor 的层添加高斯模糊。 下面的代码在标题文本周围添加了一个框并且工作正常,我只是想让白色变得模糊。 title.layer.borderColor = U
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 关闭 4 年前。 这个问题是由于打字错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic
为什么在 CSS 中通过 Javascript 更改样式时使用 background-color 不起作用? 这个有效: document.getElementById("circ").style.b
我有下面的 javascript 函数,当一个新文档被添加到列表时,它会闪烁链接的 bg 3 次。 这第一次工作正常,但随后对该函数的调用导致闪烁变得困惑。越叫越怪异的闪烁行为。 我在 IE8 和最新
如果我在属性检查器的图像/ ImageView 中设置图像,则以下后续调用不起作用: picture.backgroundColor = UIColor.greenColor() 如果我在代码中设置图
我正在尝试制作一个网站,但遇到了问题。当我在 Chrome 中运行它时,我得到:“无法设置未定义的属性‘backgroundColor’”。我不明白为什么我会得到这个。我的 var 不是数组(只是一个
我在我的应用程序中使用新的(在 iOS 7 中)UIPopoverController.backgroundColor 设置来根据需要更改弹出框的颜色,但我发现使用此设置会导致每当我打开我的popov
我有以下控制权。我想更改某些事件触发器的背景颜色。我想将此 clrGray 资源设为某些事件点击时的颜色。 我试过以下方法,但没有用:( XAM: CS: //On Some event /
我有以下控制权。我想更改某些事件触发器的背景颜色。我想将此 clrGray 资源设为某些事件点击时的颜色。 我试过以下方法,但没有用:( XAM: CS: //On Some event /
我正在构建一个排序算法可视化工具。这些项目中的每一项都是 div,backgroundColor 设置为白色。 当算法运行时,他将 backgroundColor 设置为橙色以显示哪些项目已更改。 但
我正在尝试更改 OSX 应用程序的标题栏颜色。使用 window!.backgroundColor = .... 有时有效,但其他则无效。或者更具体地说,它有时在运行应用程序时起作用,而不是在其他应用
这是我的问题: var mycss = window.getComputedStyle(myelement); 返回一个 CSSStyleDeclaration 对象: CSSStyleDeclara
我是一名优秀的程序员,十分优秀!