Color调色板 (React版)

ゝ一纸荒年。 2022-12-31 12:28 351阅读 0赞

案例:Color调色板

在这里插入图片描述
兄弟组件之间的数据传递方式:
现将数据传递给父组件,父组件再将数据传递给另一个子组件。
在这里插入图片描述

  1. const { Component,Fragment} = React;
  2. //子组件 ColorBoard
  3. class ColorBoard extends Component{
  4. render(){
  5. const { color} = this.props;
  6. return(
  7. <Fragment>
  8. <div className="colorBoard" style={ { backgroundColor:color}}></div>
  9. </Fragment>
  10. )
  11. }
  12. }
  13. //子组件 ColorSelector
  14. class ColorSelector extends Component{
  15. constructor(props){
  16. super(props);
  17. this.state = {
  18. colorItem:[255,255,255]
  19. }
  20. }
  21. //当滑竿发生改变时
  22. rangeChange(event,index){
  23. const { onColorChange} = this.props;
  24. let colorItem = [...this.state.colorItem];
  25. colorItem[index] = parseInt(event.target.value);
  26. this.setState({
  27. colorItem
  28. })
  29. onColorChange(this.state.colorItem);
  30. }
  31. render(){
  32. return(
  33. <Fragment>
  34. {
  35. this.state.colorItem.map((item,index)=>{
  36. return (
  37. <input type="range" min={ 0} max={ 255} value={ item} key={ index}
  38. onChange={ ()=>this.rangeChange(event,index)}/>
  39. )
  40. })
  41. }
  42. </Fragment>
  43. )
  44. }
  45. }
  46. //父组件Color
  47. class Color extends Component{
  48. constructor(props){
  49. super(props);
  50. this.state = {
  51. color:'#FFFFFF'
  52. }
  53. }
  54. colorChange(myColor){
  55. let color = '#' + myColor.map(item=>{
  56. return item>15?item.toString(16):'0'+item.toString(16)
  57. }).join('').toUpperCase();
  58. this.setState({
  59. color
  60. })
  61. }
  62. render(){
  63. return (
  64. <Fragment>
  65. <div className="container">
  66. <div className="row">
  67. <div className="col-md-12">
  68. <h1>React兄弟组件的数据传递 <small>Color调色板</small></h1><hr/>
  69. </div>
  70. </div>
  71. <div className="row">
  72. <div className="col=md=5">
  73. <ColorBoard color={ this.state.color}></ColorBoard>
  74. </div>
  75. <div className="col-md-5">
  76. <div>颜色代码:{ this.state.color}</div>
  77. <ColorSelector onColorChange={ this.colorChange.bind(this)}></ColorSelector>
  78. </div>
  79. </div>
  80. </div>
  81. </Fragment>
  82. )
  83. }
  84. }
  85. ReactDOM.render(
  86. <Color></Color>,
  87. document.getElementById('colorPalette')
  88. )

发表评论

表情:
评论列表 (有 0 条评论,351人围观)

还没有评论,来说两句吧...

相关阅读

    相关 R语言调色板——colors()

    R语言中画图避免不了使用颜色,在R语言中也有很多颜色得包和函数,比如彩虹色、`rgb`、`colors`还有不同色系得调色板等等。今天我们使用`colors`来展示其中得`65