在react js中将函数从父级传递给子级

时间:2021-04-05 12:10:48

标签: javascript reactjs

我编写了一个 Box.js 类,它渲染一个 div(变成盒子或正方形的形状)和另一个文件 RandColor.js,它包含一个函数来生成不同的随机 rgb 值,这只是一个辅助函数并被导入到父类 BoxContainer.js。 BoxContainer 渲染 30 个盒子,并通过地图内置函数在 RandColor.js 文件的帮助下为每个盒子分配不同的颜色。该程序运行良好,但没有将我的 RandColor.js 函数分别导入 BoxContainer.jsBox.js 文件并更改单击 div 时的状态(框的颜色),我想将 RandColor.js 函数导入到仅是 BoxContainer.js 的父文件中,然后将其作为prop 到 Individual Box.js 组件以更改状态(框的颜色)。 以下是我的三个文件的代码。

import React, { Component } from 'react'
import {RandColor} from './RandColor';
import Box from './Box';
import './BoxContainer.css';


class BoxContainer extends Component{
     static defaultProps = {
          numBoxes: 21
     }

     render(){
          const boxes = Array.from({length: this.props.numBoxes}).map( () => (
               <Box colors={RandColor()} />
          ))

          return (
               <div className="BoxContainer">
                    {boxes}
               </div>
          )
     }
}

export default BoxContainer;

这是我的父组件 BoxContainer.js

import React, { Component } from 'react';

import './Box.css';
import {RandColor} from './RandColor';

class Box extends Component{

     constructor(props){
          super(props);
          this.state = {
               color: this.props.colors,
          }
     }

     changeColor(){
          let newColor = RandColor();
          this.setState({
               color: newColor
          })
     }

     handleClick(){
          this.changeColor();
     }

     render(){

          return (
               <div className="Box" 
                    style={{backgroundColor: this.state.color}} 
                    onClick={() => {this.handleClick()}}>
               </div>
          )
     }
}

export default Box;

这是我的子组件 Box.js

function RandColor(){
     let r = Math.floor(Math.random() * 256 );
     let g = Math.floor(Math.random() * 256 );
     let b = Math.floor(Math.random() * 256 );
     const rgbValue = `rgb(${r}, ${g}, ${b})`;
     return rgbValue;
}

export {RandColor};

这是我生成随机 rgb 值的辅助函数,RandColor.js

0 个答案:

没有答案