gpt4 book ai didi

reactjs - 如何在 React 状态对象数组中设置属性

转载 作者:行者123 更新时间:2023-12-03 14:08:55 27 4
gpt4 key购买 nike

我有 2 个 React 组件 Memory 和子组件 MemoryShape

在内存组件中,我有一个方法 newGame,当我单击按钮时,它将 4 个随机 MemoryShapes 设置为紫色,但是当我单击所有形状时,所有形状都变为紫色,而不是我想要的 4

import React, { Component } from 'react';
import './memory.css';
import MemoryShape from './MemoryShape';
import randomShape from './helpers/help';

class Memory extends Component {
constructor(props) {
super(props);
this.state = {
memoryshapes: new Array(16).fill(Math.random() * 1321132),


};

this.preInitGame = this.preInitGame.bind(this);

this.newGame = () => {
const [...shapes] = this.state.memoryshapes;
const coloredShapesIndexes = randomShape(4, 15);
coloredShapesIndexes.forEach((value) => {
shapes[value].shape.style.backgroundColor = 'purple';
});

console.log(shapes);
this.setState({ memoryshapes: shapes });
};
}

componentWillMount() {
this.preInitGame();
}


preInitGame() {
let [...memoryshapes] = this.state.memoryshapes;
const data = {
shape: {
style: {
setColor(nextColor) {
this.backgroundColor = nextColor;
},
backgroundColor: 'green',
},
},
};
memoryshapes = memoryshapes.map((value) => {
let newValue = value;
newValue = data;

return newValue;
});

this.setState({ memoryshapes });
}


render() {
const shapes = this.state.memoryshapes.map((value, index) => {
const arrkey = index + value;
return (<MemoryShape
key={arrkey}
tabIndex={index}
backgroundColor={value.shape.style.backgroundColor}
/>);
});
return (
<div>
{shapes}
<br />
<button
style={{
padding: 20,
marginLeft: 300,
}}
onClick={this.newGame}
>
Start Game
</button>
<MemoryShape
tabIndex={-124}
backgroundColor="blue"
/>
</div>
);
}
}

export default Memory;

class MemoryShape extends Component {
constructor(props) {
super(props);
this.state = { backgroundColor: 'green' };

this.changeColor = () => {

};
this.handleKeyDown = () => {

};
}
componentWillReceiveProps(nextProps) {
console.log(nextProps.backgroundColor);
this.setState({ backgroundColor: nextProps.backgroundColor });
}


render() {
return (
<div
className="memory-shape"
onKeyDown={this.handleKeyDown}
onClick={this.changeColor}
role="button"
tabIndex={this.props.tabIndex}
backgroundColor={this.props.backgroundColor}
style={{ backgroundColor: this.state.backgroundColor }}
/>
);
}
}

MemoryShape.propTypes = {
backgroundColor: PropTypes.string,
tabIndex: PropTypes.number.isRequired,
};
MemoryShape.defaultProps = {
backgroundColor: 'transparent',
};

export default MemoryShape;

最佳答案

确保对象数组中有唯一的属性!只需添加 id 属性,一切正常!

关于reactjs - 如何在 React 状态对象数组中设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47555671/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com