Я пытаюсь создать генератор случайных цветов, который будет устанавливать новые случайные цвета фона из массива в элемент при нажатии.
Я создал функцию handleClick () в первом пролете, но когда я щелкаю по нему, он показывает мне следующее:
TypeError: this.state.push не является функцией
Вот мой файл ColorShifter:
import React, { Component } from "react";
import "./Colorshifter.css";
class ColorShifter extends Component {
static defaultProps = {
colors: [
"#3498db",
" #8d989f",
"#9c6faa",
"#97aa6f",
"#487459",
"#48746f",
"#cfbd67",
"#df811d",
"#f06653",
"#f0e753",
"#f70000",
"#ec00f7",
"#1d21b0",
"#464664",
"#a29967",
"#bc8abd",
"#8abdb0",
"#397254",
"#e6e6d0"
]
};
constructor(props) {
super(props);
this.state = [];
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
let r = Math.floor(Math.random() * this.props.colors.length);
this.setState((this.state[e] = this.state[r]));
}
render() {
for (var i = 0; i < this.props.colors.length; i++) {
let ran = Math.floor(Math.random() * this.props.colors.length);
const colorStyle = {
backgroundColor: this.props.colors[ran]
};
this.state.push(colorStyle);
}
return (
<div className="div">
<span onClick={this.handleClick(0)}>
<p style={this.state[0]} className="container"></p>
</span>
<span>
<p style={this.state[1]} className="container"></p>
</span>
<span>
<p style={this.state[2]} className="container"></p>
</span>
<span>
<p style={this.state[3]} className="container"></p>
</span>
<span>
<p style={this.state[4]} className="container"></p>
</span>
<span>
<p style={this.state[5]} className="container"></p>
</span>
<span>
<p style={this.state[6]} className="container"></p>
</span>
<span>
<p style={this.state[7]} className="container"></p>
</span>
<span>
<p style={this.state[8]} className="container"></p>
</span>
<span>
<p style={this.state[9]} className="container"></p>
</span>
<span>
<p style={this.state[11]} className="container"></p>
</span>
<span>
<p style={this.state[10]} className="container"></p>
</span>
<span>
<p style={this.state[12]} className="container"></p>
</span>
<span>
<p style={this.state[13]} className="container"></p>
</span>
<span>
<p style={this.state[14]} className="container"></p>
</span>
<span>
<p style={this.state[15]} className="container"></p>
</span>
<span>
<p style={this.state[16]} className="container"></p>
</span>
<span>
<p style={this.state[17]} className="container"></p>
</span>
</div>
);
}
}
export default ColorShifter;
Мой основной файл App.js:
import React from "react";
// import logo from './logo.svg';
import "./App.css";
import ColorShifter from "./ColorShifter";
function App() {
return (
<div className="App">
<ColorShifter />
</div>
);
}
export default App;
мой файл css (необязательно):
.container {
margin: 0;
padding: 0;
height: 200px;
width: 250px;
display: flex;
display: inline-block;
font-size: 0px;
flex-wrap: wrap;
}
.div {
font-size: 0;
margin: 0;
padding: 0;
}