将其中一个孩子的变化传达给父母的父母

Raf*_*lak 2 javascript reactjs

这就是我的"层次结构"看起来的样子:

Game
    Table
        TableRow
            Cell
Run Code Online (Sandbox Code Playgroud)

单击一个单元格时,我想从Game运行一个方法.React的设计与我以前的设计略有不同,我无法将我的想法转变为将Cell的变化传达给Game.最好的方法是什么?

仅供参考,我正在尝试在React.js中创建Ultimate TTT.

小智 8

你可以做的是将指向Game函数的指针作为属性传递给Child组件.例如:

var Game = React.createClass({
    gameFunction: function() {
        alert('gameFunction()');
    },
    render: function() {
        return (
            <div className="game">
                <h1>Game</h1>
                <Table gameFunction={this.gameFunction} />
            </div>
        );
    }
});

var Table = React.createClass({
    render: function() {
        return (
            <div className="table">
                <table>
                    <tr>
                        <td onClick={this.props.gameFunction}>Cell</td>
                    </tr>
                </table>
            </div>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

话虽这么说,我对React来说是全新的,我不确定这是否是实现这一目标的正确方法!

  • 是的,这是正确的 - 以这种方式线程化回调使得它明确了你的组件可能触发的回调. (3认同)