【发布时间】:2021-02-21 00:21:17
【问题描述】:
在下面的代码中,我在我的 Easy React 项目中添加了一个背景设置部分。但是我遇到了 getColor 函数的问题。 console.log 正在工作,但不明白为什么我的事件对象没有按我希望的那样工作。我收到此错误: 未捕获的类型错误:无法读取未定义的属性“目标”
import React, { Component } from 'react';
import './Background.css';
class Background extends Component {
state = {
color: '#C24C69'
};
pickColor = () => {
const arr = [ 'A', 'B', 'C', 'D', 'E', 'F', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
let hexColor = '#';
for (let i = 0; i < 6; i++) {
const rand = Math.floor(Math.random() * arr.length);
hexColor += arr[rand];
}
this.setState({ color: hexColor });
};
getColor = (evt) => {
let col = '#';
col += evt.target.value;
console.log(col);
return col;
};
setColor = () => {
let newCol = this.getColor();
this.setState({ color: newCol });
};
render() {
return (
<div className="Background" style={{ backgroundColor: this.state.color }}>
<h2>Your lucky bg color is: {this.state.color}</h2>
<button className="btn-1" onClick={this.pickColor}>
Change bg color
</button>
<h3>Wanna try your own color?</h3>
<label htmlFor="hex">
Hex #
<input onChange={this.getColor} type="text" name="hex" />
</label>
<button onClick={this.setColor}>Set</button>
</div>
);
}
}
export default Background;
【问题讨论】:
标签: javascript reactjs events