[英]Can someone explain what this line is doing
有人可以幫助我了解此功能在線發生了什么
function getContainer(container, defaultContainer) {
//this line below
container = typeof container === 'function' ? container() : container;
return ReactDOM.findDOMNode(container) || defaultContainer;
}
容器被分配了typeof容器的結果,但是如果container等於一個函數,則調用該函數。
我有點頭暈。 此代碼是從React組件Modal的材料ui文檔中提取的
意思是說:
if
container
是一個函數,則將其分配給名為container
的變量,然后將調用該函數, else
將變量container
設置為傳遞給getContainer
函數的參數container
。
您也可以這樣寫,可能更容易閱讀:
if (typeof container === 'function') {
container = container();
} else {
container = container;
}
在您的示例中,它使用的是三元運算符,這是編寫if
/ else
語句的另一種方式。 您可以在這里閱讀更多內容。
等於:
if(typeof container === 'function')container= container();
else container = container;
如果它是一個函數,它將調用container並將結果存儲在名為container的變量中。 它不是什么都不做。
首先,了解基本知識以及我們在js中引用函數/方法的方式的區別 。
假設有一個名為container的函數
function container() {
let name = 'Js';
return name;
}
console.log(container()); //js as we got the value here
console.log(typeof(container())) // string as this time we have value which of string type
console.log(typeof(container)) // function as we are pointig to function
當我們僅引用不帶()的函數名稱時,便在控制台中獲得了完整的函數結構
console.log(container);
ƒ container() {
let name = 'Js';
return name;
}
知道什么是typeof
所以在您的問題中,它檢查通過了什么,最后要知道的是
condition ? expr1 : expr2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.