首页 > 解决方案 > 如何在 React 中记录道具?

问题描述

React 新手,这只是我上课的第一天。我要做的就是当我单击一个框时记录颜色道具。

我知道我不能做 console.log(this.props.color) 因为这是引用应用程序......现在这一切都很混乱......任何提示将不胜感激。



class Boxes extends Component{
  render(props){
    return (
      <div className="boxes" onClick={this.props.getBoxColor}>
        <div className="box1" color="red"></div>
        <div className="box2" color="orange"></div>
        <div className="box3" color="yellow"></div>
        <div className="box4" color="green"></div>
        <div className="box5" color="blue"></div>
      </div>
    );
  }
}

class App extends Component {

  getBoxColor=()=>{
    console.log(this.props)
  }


  render() {
    return (
    <Boxes classColor={this.color} getBoxColor={this.getBoxColor} />
    )
  }
}


ReactDOM.render(<App />, document.getElementById('root'));




标签: javascriptreactjs

解决方案


试试这个,告诉我它是否适合你。

class Box extends React.Component {
  render() {
    const className = this.props.className;
    const color = this.props.color;
    return (
      <div
        className={className}
        color={color}
        onClick={() => console.log(color)}
      />
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <Box className="box1" color="red" />
        <Box className="box2" color="blue" />
        <Box className="box3" color="green" />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

推荐阅读