onClick还没有工作

时间:2017-11-05 18:02:55

标签: javascript reactjs components

我试图在反应中创造一个tic tac toe游戏。现在我在开始时并没有尝试立即添加逻辑。我试图在我的盒子组件上有一个onclick函数,这样它就可以读取我使用console.log点击了网格组件。但我的onclick功能出错了。另外,你认为我需要处理事件才能使它工作吗? 这是我的代码:

export default App;

class ApplicationComponent extends React.Component {

   clicked(event){

        console.log(event.target)
    }

    render() {
        return (
            <div>Application Component</div>
        );
    }
    resetBoard(){
        console.log("what up world");
    }
    checkingWon(){
        console.log("what up world 2")
    }
}
class GridComponent extends React.Component {
onGreet(){
    console.log("grid")
}
    render() {
        return (
            <div className="grid">
                <BoxComponent/>
                <BoxComponent/>
                <BoxComponent/>
                <BoxComponent/>
                <BoxComponent/>
                <BoxComponent/>
                <BoxComponent/>
                <BoxComponent/>
                <BoxComponent/>
            </div>
        );
    }
}

class BoxComponent extends React.Component {

    render() {
        return (
            <div className="box" onClick={(BoxComponent)=>
                this.click.bind(this.onGreet)}>

            </div>
        )
    }
}

1 个答案:

答案 0 :(得分:0)

BoxComponent没有onGreet方法。如果您希望BoxComponent调用GridComponent的{​​{1}}方法,则需要将该函数作为道具传递给其子项:

onGreet

}

然后,从孩子那里打电话给那个道具:

class GridComponent extends React.Component {
  onGreet(){
    console.log("grid")
  }
  render() {
    return (
      <div className="grid">
        <BoxComponent onClick={this.onGreet}/>
        <BoxComponent onClick={this.onGreet}/>
        <BoxComponent onClick={this.onGreet}/>
        <BoxComponent onClick={this.onGreet}/>
        <BoxComponent onClick={this.onGreet}/>
        <BoxComponent onClick={this.onGreet}/>
        <BoxComponent onClick={this.onGreet}/>
        <BoxComponent onClick={this.onGreet}/>
        <BoxComponent onClick={this.onGreet}/>
      </div>
    );
}