React.js:将父级的事件附加到子级

pis*_*hio 10 javascript reactjs

如下例所示,我希望MyComponent动态地将"onClick"事件附加到其子节点.onClick事件应该触发应该能够调用单击元素方法"getValue"的alertView.

JSFiddle:http://jsfiddle.net/2g638bp8/

这该怎么做?谢谢

var MyComponent = React.createClass({
    alertValue: function () {
        // RETRIEVE THE CHILD HERE
        alert(child.getValue());
    },
    render: function () {
        var children = React.Children.map(this.props.children, function (c, index) {
            return React.addons.cloneWithProps(c, {
                ref: 'child-' + index
            });
        });
        return (
            <div>
                {children}
            </div>
        );
    }
});

var MySubComponent = React.createClass({
    getValue: function () {
        return this.props.val;
    },
    render: function () {
        return (
            <div>{this.props.val}</div>
        );
    }
});

React.render(
    <div>
        <MyComponent>
            <MySubComponent val="1" />
            <MySubComponent val="2" />
            <MySubComponent val="3" />
        </MyComponent>
    </div>,
    document.getElementById('container')
);
Run Code Online (Sandbox Code Playgroud)

Wir*_*rie 12

您无法在React中调用子组件上的方法.您只能设置属性.(child实际上是ReactElement包含有关类和相关属性的信息.它不是您创建的组件的实例).

所以,你可以想想这一个稍微不同的方式,并移动onClickMySubComponent:

var MyComponent = React.createClass({
    onHandleGiveValue: function (value) {
        alert(value);
    },
    render: function () {
        const children = React.Children.map(this.props.children, child => React.cloneElement(child, { onGiveValue: this.onHandleGiveValue.bind(this) }));
        return (
            <div>
                {children}
            </div>
        );
    }
});

var MySubComponent = React.createClass({
    handleClick: function() {
        this.props.onGiveValue(this.props.val);
    },
    getValue: function () {
        return this.props.val;
    },
    render: function () {
        return (
            <div onClick={ this.handleClick } >{this.props.val}</div>
        );
    }
});

React.render(
    <div>
        <MyComponent>
            <MySubComponent val="1" />
            <MySubComponent val="2" />
            <MySubComponent val="3" />
        </MyComponent>
    </div>,
    document.getElementById('container')
);
Run Code Online (Sandbox Code Playgroud)

通过这样做,您的代码可以将当前值作为事件传递给父组件.我已经从MySubComponent名为的类中创建了一个新事件onGiveValue.现在只是传递价值this.props.val.但是,它当然可以是任何东西.

  • 感谢这个有用的答案 - 现在是否值得更新它和你的小提琴使用`React.cloneElement`而不是..?(由于'cloneWithProps`被弃用) (3认同)