Color调色板 (React版)
案例:Color调色板
兄弟组件之间的数据传递方式:
现将数据传递给父组件,父组件再将数据传递给另一个子组件。
const { Component,Fragment} = React;
//子组件 ColorBoard
class ColorBoard extends Component{
render(){
const { color} = this.props;
return(
<Fragment>
<div className="colorBoard" style={ { backgroundColor:color}}></div>
</Fragment>
)
}
}
//子组件 ColorSelector
class ColorSelector extends Component{
constructor(props){
super(props);
this.state = {
colorItem:[255,255,255]
}
}
//当滑竿发生改变时
rangeChange(event,index){
const { onColorChange} = this.props;
let colorItem = [...this.state.colorItem];
colorItem[index] = parseInt(event.target.value);
this.setState({
colorItem
})
onColorChange(this.state.colorItem);
}
render(){
return(
<Fragment>
{
this.state.colorItem.map((item,index)=>{
return (
<input type="range" min={ 0} max={ 255} value={ item} key={ index}
onChange={ ()=>this.rangeChange(event,index)}/>
)
})
}
</Fragment>
)
}
}
//父组件Color
class Color extends Component{
constructor(props){
super(props);
this.state = {
color:'#FFFFFF'
}
}
colorChange(myColor){
let color = '#' + myColor.map(item=>{
return item>15?item.toString(16):'0'+item.toString(16)
}).join('').toUpperCase();
this.setState({
color
})
}
render(){
return (
<Fragment>
<div className="container">
<div className="row">
<div className="col-md-12">
<h1>React兄弟组件的数据传递 <small>Color调色板</small></h1><hr/>
</div>
</div>
<div className="row">
<div className="col=md=5">
<ColorBoard color={ this.state.color}></ColorBoard>
</div>
<div className="col-md-5">
<div>颜色代码:{ this.state.color}</div>
<ColorSelector onColorChange={ this.colorChange.bind(this)}></ColorSelector>
</div>
</div>
</div>
</Fragment>
)
}
}
ReactDOM.render(
<Color></Color>,
document.getElementById('colorPalette')
)
还没有评论,来说两句吧...