首页 > 解决方案 > 将函数作为对象的值传递

问题描述

我正在使用reactjs。

我想将一个action数组传递给我的组件。我的动作是这样的:

const actions = [
                 {
                   'action':'delete',
                   'on':'id',
                   'onClick':this.delete()
                 },
                 {
                   'action':'detail',
                   'on':'id',
                   'onClick':this.detail()
                 }
                ]

<MyComponent actions={actions}/>

但我不知道是否可以将函数传递给对象内部的组件。

更新

现在如何传递参数?我想将参数传递MyComponent给父组件。

标签: javascriptreactjs

解决方案


是的,您可以在对象内部传递函数,但不应调用。试试这个

let action ={
    delete:{
        on:'id',
        onClick:this.delete.bind(this)
    },
    details:{
        on:'id',
        onClick:this.detail.bind(this)
    }
}
<MyComponent actions={actions}/>

如果要将变量从子级传递给父级,请使用 lambda 函数

class MyComponent extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <button onclick={e=>{
                //here you can pass any param from child to parent
                let params={}; //your params
                this.props.actions.delete(params);
            }}>Delete</button>

            <button onclick={e=>{
                //here you can pass any param from child to parent
                let params={}; //your params
                this.props.actions.detail(params);
            }}>Details</button>
            </div>
        )
    }

}

推荐阅读