[英]How to send a two argument function in props in React?
I have a function which takes two arguments earlier it used to take only one argument so to pass it in props as this:- 我有一个函数,它前面需要两个参数,它过去只需要一个参数,因此可以在props中传递它,如下所示:
mixed1.map((cat1) => (<ServicesCategoryOption category1={cat1.categories} setacatid={i=>this.setacatid(i)}/>))
But now I changed setacatid as:- 但是现在我将setacatid更改为:
setacatid(a,b){
console.log(b);
this.setState({
catidofclicked:a,
catnameofclicked:b
},function(){
localStorage.setItem('selecteditem',this.state.catidofclicked);
localStorage.setItem('selectedname',this.state.catnameofclicked);
});
}
So it takes two arguments a and b how to pass it in props now? 所以需要两个参数a和b现在如何在道具中传递它?
You can pass multiple arguments to the event handlers when you are using the arrow function syntax like 使用箭头函数语法时,可以将多个参数传递给事件处理程序
mixed1.map((cat1) => (
<ServicesCategoryOption
category1={cat1.categories}
setacatid={(a, b)=>this.setacatid(a, b)}
/>
))
or you can simply write 或者你可以简单地写
mixed1.map((cat1) => (
<ServicesCategoryOption
category1={cat1.categories}
setacatid={(...args)=>this.setacatid(...args)}
/>
))
which can simply be written as 可以简单地写成
mixed1.map((cat1) => (
<ServicesCategoryOption
category1={cat1.categories}
setacatid={this.setacatid}
/>
))
The only advantage of using the first method is that you can pass custom values too like 使用第一种方法的唯一优点是您也可以像这样传递自定义值
mixed1.map((cat1) => (
<ServicesCategoryOption
category1={cat1.categories}
setacatid={(...args)=>this.setacatid(1, ...args)}
/>
))
in which way you can pass a many parameters from child and receive them in the function without worrying about adding a parameter everytime you want to add a new one 这样,您可以从child传递许多参数并在函数中接收它们,而不必担心每次要添加新参数时都会添加参数
You can do whatever you want: 你想做什么,就可以做什么:
<ServicesCategoryOption
category1={cat1.categories}
setacatid={i=>this.setacatid(i,10)}
/>
<ServicesCategoryOption
category1={cat1.categories}
setacatid={(i, j)=>this.setacatid(i, j)}
/>
<ServicesCategoryOption
category1={cat1.categories}
setacatid={this.setacatid}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.