视频地址
main.js
import React from "react"
import { render } from "react-dom"
import App from "./App.js"
render(
<App></App>,
document.getElementById("app-container")
)
App.js
// 引入 React 和 Component 组件
import React, { Component } from "react";
import Bar from "./components/Bar/Bar.js";
import "./app.less";
class App extends Component {
constructor() {
super()
this.state = {
r: 128,
g: 128,
b: 128
}
// 三个 Bar 实例
this.bars = ['r', 'g', 'b'].map((item, index) => {
return <Bar key={index} v={this.state[item]} color={item} setColor={(this.setColor).bind(this)}></Bar>
})
}
// 设置函数,可以改变 color 颜色为 value
setColor(color, value) {
this.setState({ [color]: value })
}
render() {
return (
<div>
<div className="box" style={{ "backgroundColor": `rgb(${this.state.r},${this.state.g},${this.state.b})` }}></div>
{this.bars}
</div>
)
}
}
//向外暴露
export default App;
app.less
.box {
200px;
height: 200px;
border: 1px solid #333;
}
Bar.js
import React from "react";
import "./css.less";
import {PropTypes} from "prop-types";
class Bar extends React.Component {
constructor(props) {
super()
this.state = {
v: props.v
}
// 绑定this
this.change = (this.change).bind(this)
this.setColor = props.setColor
}
// 改变颜色
change(event) {
this.setState({'v': parseInt(event.target.value)})
this.setColor(this.props.color, this.state.v)
}
render() {
return (
<div className="Bar_kaola">
<div className="bar">
{this.props.v}
<input type="range" min="0" max="255" value={this.state.v} onChange={this.change} />
<input type="number" min="0" max="255" value={this.state.v} onChange={this.change} />
</div>
</div>
)
}
}
Bar.propTypes = {
v : PropTypes.number.isRequired,
color : PropTypes.string.isRequired,
setColor : PropTypes.func.isRequired
}
//向外暴露
export default Bar
Bar/css.less:
.Bar_kaola {
.bar {
input[type="number"] {
width: 50px;
position: relative;
top: -2px;
}
margin-bottom: 10px;
}
}
package.json:
"devDependencies": {
"@babel/core": "^7.4.4",
"@babel/plugin-transform-runtime": "^7.4.4",
"@babel/preset-env": "^7.4.4",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"less": "^3.9.0",
"less-loader": "^5.0.0",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"style-loader": "^0.23.1",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.2"
},
"dependencies": {
"@babel/runtime": "^7.4.4"
}
webpack.config.js
const path = require('path');
module.exports = {
entry: "./app/main.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "all.js"
},
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /.less$/,
use: [
{
loader: "style-loader" // creates style nodes from JS strings
},
{
loader: "css-loader" // translates CSS into CommonJS
},
{
loader: "less-loader" // compiles Less to CSS
}
]
}
]
},
watch: true
}