javascript - 将函数作为对象的值传递
问题描述
我正在使用reactjs。
我想将一个action
数组传递给我的组件。我的动作是这样的:
const actions = [
{
'action':'delete',
'on':'id',
'onClick':this.delete()
},
{
'action':'detail',
'on':'id',
'onClick':this.detail()
}
]
<MyComponent actions={actions}/>
但我不知道是否可以将函数传递给对象内部的组件。
更新
现在如何传递参数?我想将参数传递MyComponent
给父组件。
解决方案
是的,您可以在对象内部传递函数,但不应调用。试试这个
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>
)
}
}
推荐阅读
- google-apps-script - 如何将值推送到列 Google Sheets App Script
- android - Android Studio 模拟器不再响应
- kubernetes - Kubernetes MLflow 服务 Pod 连接
- javascript - 如何确定数组中一定数量的对象是否在JS中包含具有相同值的相同属性
- groovy - 如何从 Jenkinsfile(管道)运行 Groovy 构建后脚本?
- paypal - 如何创建 Paypal 开发者帐户(不是沙盒)
- python - Django Admin tabularInline 非常慢的请求
- sql-server - 连接两个表,需要在 ON 子句中有 MAX 聚合函数
- sed - sed 匹配多个匹配项中的第一个模式
- c++ - 从 main.cpp 中的另一个文件调用函数