将方法作为道具传递给所有孩子

时间:2016-05-15 18:10:33

标签: reactjs

尝试将方法作为道具传递给所有孩子。但是在控制台中打印子道具时,它显示未定义。

控制台输出:

Object {openLightbox: undefined, closeLightbox: undefined, setLightboxState: undefined, key: 0}   

将openLightbox,closeLightbox和setLightboxState方法作为道具传递给所有子项。在变量childProps中设置它。

var Lightbox = React.createClass({

    getInitialState: function(){
        return { display: false };
    },

    componentWillMount: function(){
        if (this.props.data)
            this.setState(this.props.data);
    },

    openLightbox: function(){
        this.setState({display: true});
    },

    closeLightbox: function(){
        this.setState({display: false});
    },

    setLightboxState: function(obj){
        this.setState(obj);
    },

    render: function(){
        var childrenWithProps = this.props.children.map(function(child, i) {
            var childProps = {
                openLightbox: this.openLightbox,
                closeLightbox: this.closeLightbox,
                setLightboxState: this.setLightboxState,
                key: i
            };
            console.log(childProps)
            for (var j in this.state){
                childProps[j] = this.state[j];
            }

            var childWithProps = React.cloneElement(child, childProps);

            return childWithProps;
        });

        return (
            <div>
                {childrenWithProps}
            </div>
        );
    }
});

2 个答案:

答案 0 :(得分:2)

this中的{p> .map指的是全局范围(在浏览器中为windowundefined,如果您使用strict mode),则表示没有方法{{ 1}},openLightbox等。您可以通过第二个参数为closeLightbox设置this

.map

答案 1 :(得分:0)

你不应该直接迭代this.props.children,React有一个顶级的API来映射this.props.children(https://facebook.github.io/react/docs/top-level-api.html)。

然后地图中的函数将windowundefined作为this,因此您应该使用箭头函数(在ES2015中为=&gt;)或.bind(this)来链接React Component实例到this

var childrenWithProps = React.Children.map(this.props.children, function(child) { ... }.bind(this))