Javascript 传递函数作为对象的值
我用的是reactjs 我想向我的组件传递一个动作数组。我的行动是这样的:Javascript 传递函数作为对象的值,javascript,reactjs,Javascript,Reactjs,我用的是reactjs 我想向我的组件传递一个动作数组。我的行动是这样的: const actions = [ { 'action':'delete', 'on':'id', 'onClick':this.delete() }, { 'actio
const actions = [
{
'action':'delete',
'on':'id',
'onClick':this.delete()
},
{
'action':'detail',
'on':'id',
'onClick':this.detail()
}
]
<MyComponent actions={actions}/>
但我不知道是否有可能将函数传递给对象内部的组件
更新
现在如何传递参数?我想将参数从MyComponent传递到父组件。将调用您的函数,请尝试:
const actions = [
{
'action':'delete',
'on':'id',
'onClick':this.delete
},
{
'action':'detail',
'on':'id',
'onClick':this.detail
},
]
将调用您的函数,请尝试:
const actions = [
{
'action':'delete',
'on':'id',
'onClick':this.delete
},
{
'action':'detail',
'on':'id',
'onClick':this.detail
},
]
是的,您可以在对象内部传递函数,但不应调用。试试这个
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>
)
}
}
是的,您可以在对象内部传递函数,但不应调用。试试这个
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>
)
}
}
我认为你失去了背景,所以这是不被承认的。 也许你应该这样做:
const actions = [
{
'action':'delete',
'on':'id',
'onClick':(() => this.delete(params))
},
{
'action':'detail',
'on':'id',
'onClick':(() => this.detail(params))
},
]
<MyComponent actions={actions}/>
我认为你失去了背景,所以这是不被承认的。 也许你应该这样做:
const actions = [
{
'action':'delete',
'on':'id',
'onClick':(() => this.delete(params))
},
{
'action':'detail',
'on':'id',
'onClick':(() => this.detail(params))
},
]
<MyComponent actions={actions}/>
删除,将其用作onClick:this.delete删除,将其用作onClick:this.delete不必要的包装将函数转换为arrow函数,因此“this”将被绑定必要的包装将函数转换为arrow函数,因此“this”将被绑定。未定义参数,我想将参数从MyComponent传递到父组件。我已更改了actions变量的格式。并提供了子组件的示例@未定义S.M_Emamianparams,我想将参数从MyComponent传递到父组件。我已更改了actions变量的格式。并提供了子组件的示例@S.M_Emamian