Имеется код рандомно заполнящий поле двумя цветами. Массив при инициализации формирую методом generateData
:
const getStyle = style => Object.assign({}, style);
const universeStyle = length => ({
position: "relative",
width: `${length * 10}px`,
height: `${length * 10}px`,
fontSize: '0',
border: "1px solid #222"
});
const cellStyle = item => ({
background: `${item.color}`,
display: "inline-block",
boxSizing: "border-box",
width: "10px",
height: "10px",
//border: "1px solid grey"
});
const Cell = ({ item }) => (
<div x={item.x} y={item.y} style={getStyle(cellStyle(item))} />
);
class Universe extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.generateData(props.width)
};
}
getColor(colors = ["white", "black"]) {
return colors[Math.floor(Math.random() * colors.length)];
}
generateArray(width, pos) {
return Array.from({ length: width }).map((item, index) => ({
y: pos,
x: index,
color: this.getColor()
}));
}
generateData(width) {
return Array.from({ length: width }).map((item, index) =>
this.generateArray(width, index)
);
}
render() {
return (
<div style={getStyle(universeStyle(this.props.width))}>
{this.state.data.map(item => item.map(item => <Cell item={item} />))}
</div>
);
}
}
ReactDOM.render(<Universe width={70} />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Какой метод компонента использовать, чтобы, например, раз в секунду, запускалось перестроение поля с новым массивом?