reactjs - 将方法作为 Prop 传递给所有 child

标签 reactjs

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

控制台输出:

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

将 openLightbox、closeLightbox 和 setLightboxState 方法作为 props 传递给所有子项。将其设置在变量 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>
        );
    }
});

最佳答案

.map 中的

this 引用全局范围(在浏览器中它是 windowundefined 如果您使用严格模式),其中没有方法openLightboxcloseLightbox等。您可以为设置this。通过第二个参数映射

this.props.children.map(function(child, i) {
  ...
}, this);
___^^^^_

关于reactjs - 将方法作为 Prop 传递给所有 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37241912/

相关文章:

javascript - 如何在react js中的map函数中进行增量

javascript - 我无法在 Material-UI 中编辑文本字段

javascript - 如何将自定义图标添加到NativeBase

reactjs - 同构/通用渲染的 React 15 应用程序因 Cloudflare HTTP 代理而中断 ("orange cloud")

javascript - 重新渲染时组件崩溃

javascript - 鼠标悬停在 ag 网格上时行突出显示 react

javascript - react 。 onCopy 事件的 preventDefault() 不起作用

reactjs - Jest : SVG require causes "SyntaxError: Unexpected token <"

javascript - 如何在 reactjs 中包含外部 JavaScript 库

reactjs - 如何将所有父 Props 传递给使用 {this.props.children} 的所有嵌套路由子级