简体   繁体   English

如何将可选参数传递给反应中的 function 和 javascript?

[英]How to pass optional parameter to a function in react and javascript?

i want to set an optional parameter to a function using javascript.我想使用 javascript 为 function 设置一个可选参数。 i have a function defined like below,我有一个 function 定义如下,

const function1 = () => {
    setValue(!open);
};

i call it like below in other function我在其他 function 中这样称呼它

const main_function = () => {
    function1();
}

now i want to pass an optional parameter to function1 to accept an optional parameter that sets it to true or false instead of toggling based on previous value.现在我想将一个可选参数传递给 function1 以接受一个将其设置为 true 或 false 的可选参数,而不是根据先前的值进行切换。

how can i fix this.我怎样才能解决这个问题。 could someone help me with this thanks.有人可以帮我这个谢谢。

I hope this helps someone, you can just set the value to null like code below:我希望这对某人有所帮助,您可以将值设置为 null ,如下面的代码:

 const function1 = ({arg1=null, arg2= false, arg3, ...}) => {
  
 }

You can check the if the argument is defined or not, like:您可以检查参数是否已定义,例如:

const function1 = (arg) => {
  setValue(arg === undefined ? !open : arg);
};

As far as I can understand you want something like this.据我所知,你想要这样的东西。

const function1 = (param) => {
    setValue(params ? true : false);
}

It will set true if param is available otherwise false.如果param可用,它将设置为true ,否则设置为 false。 Correct me if I'm wrong.如我错了请纠正我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM