Reputation: 17383
I'm using reactjs.
I want to pass an action
array to my component. My action is like this:
const actions = [
{
'action':'delete',
'on':'id',
'onClick':this.delete()
},
{
'action':'detail',
'on':'id',
'onClick':this.detail()
}
]
<MyComponent actions={actions}/>
but I don't know if it is possible to pass a function to component inside objects.
updated
Now how to pass parameter? I want to pass parameter from MyComponent
to parent component.
Upvotes: 1
Views: 145
Reputation: 1146
Yes you can pass the function inside a object but you should not call. try this
let action ={
delete:{
on:'id',
onClick:this.delete.bind(this)
},
details:{
on:'id',
onClick:this.detail.bind(this)
}
}
<MyComponent actions={actions}/>
If you want to pass variable from child to parent then use a lambda function
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>
)
}
}
Upvotes: 3
Reputation: 1194
I think you are loosing the context so this
is not recognized.
Maybe you should do this:
const actions = [
{
'action':'delete',
'on':'id',
'onClick':(() => this.delete(params))
},
{
'action':'detail',
'on':'id',
'onClick':(() => this.detail(params))
},
]
<MyComponent actions={actions}/>
Upvotes: 0
Reputation: 14610
The () will call your function, try:
const actions = [
{
'action':'delete',
'on':'id',
'onClick':this.delete
},
{
'action':'detail',
'on':'id',
'onClick':this.detail
},
]
Upvotes: 2