我建立了一个简单的应用程序,可让您单击彩色圆点并随机更改其每种颜色,还提供了rgb代码。我是一名反应灵敏的初学者,所以请随便找个想法。
我可以使用它,但是我的代码太长了,与之相反!而且我知道必须有一种方法可以将所有这些事件处理程序打包为一个...
预先感谢您帮助我整理代码并学习...
APP.JS
import React, { Component } from 'react';
import logo from './friedhead.svg';
import './App.css';
import Colour from './Colour/Colour';
class App extends Component {
state = {
a1: 138, a2: 131, a3: 198,
b1: 1, b2: 131, b3: 198,
c1: 138, c2: 131, c3: 3,
d1: 138, d2: 12, d3: 198
}
colourCreator = () => {
return Math.floor(Math.random() * 250) + 1
}
//wow there must be a better way to do this
updateAHandler = ( event ) => {
this.setState( {
a1: this.colourCreator(), a2: this.colourCreator(), a3: this.colourCreator()
})
}
updateBHandler = ( event ) => {
this.setState( {
b1: this.colourCreator(), b2: this.colourCreator(), b3: this.colourCreator()
})
}
updateCHandler = ( event ) => {
this.setState( {
c1: this.colourCreator(), c2: this.colourCreator(), c3: this.colourCreator()
})
}
updateDHandler = ( event ) => {
this.setState( {
d1: this.colourCreator(), d2: this.colourCreator(), d3: this.colourCreator()
})
}
//wow there must be a better way to do this
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1>30 days of React</h1>
<h2>Day Three / Random Colour Picker</h2>
</header>
<div className="container">
<Colour
clicked={this.updateAHandler}
c1={this.state.a1.toString()}
c2={this.state.a2.toString()}
c3={this.state.a3.toString()}
id={'a'}
/>
<Colour
clicked={this.updateBHandler}
c1={this.state.b1.toString()}
c2={this.state.b2.toString()}
c3={this.state.b3.toString()}
id={'b'}
/>
</div>
<div className="container">
<Colour
clicked={this.updateCHandler}
c1={this.state.c1.toString()}
c2={this.state.c2.toString()}
c3={this.state.c3.toString()}
id={'c'}
/>
<Colour
clicked={this.updateDHandler}
c1={this.state.d1.toString()}
c2={this.state.d2.toString()}
c3={this.state.d3.toString()}
id={'d'}
/>
</div>
</div>
);
}
}
export default App;
COLOUR.JS
import React from 'react';
const colour = ( props ) => {
let newColour = ("rgb(" + props.c1 +", "+ props.c2 +", "+ props.c3 +")");
const outputstyle = {
textAlign: 'center',
fontSize: 'calc(5px + 2vmin)',
color: 'black',
paddingTop: '10vw'
};
const divstyle = {
margin: '20px',
backgroundColor: newColour,
textAlign: 'center',
width: '30vw',
height: '30vw',
borderRadius: '100%',
display: 'inline-block'
};
return (
<div style={divstyle}
onClick={props.clicked}>
<h1 style={outputstyle}>{newColour}</h1>
</div>
);
};
export default colour;
答案 0 :(得分:0)
改进代码的最快方法如下:
updateHandler(container){
const newState = {}
newState[container + "1"] = this.colourCreator()
newState[container + "2"] = this.colourCreator()
newState[container + "3"] = this.colourCreator()
this.setState(newState)
}
....
<Colour
clicked={() => this.updateHandler("c")}
c1={this.state.c1.toString()}
c2={this.state.c2.toString()}
c3={this.state.c3.toString()}
id={'c'}
/>
这样,每个容器只有一个处理函数。
您可以在这里进行很多改进。如何将此发布到codereview stackexchange?