Last active
February 7, 2023 03:11
-
-
Save relyky/5f156e97d3f609fe0d2e72b1b4dab19c to your computer and use it in GitHub Desktop.
CSS, utils, clsx, C#, 仿 React 的 clsx 函式。className helper。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Utils | |
{ | |
/// <summary> | |
/// 仿 React 的 clsx 函式。 | |
/// 註:基於 C#10 語法限制只能有限實作部份能力。 | |
/// </summary> | |
/// <param name="cssClassList">支援 string | ValueTuple(string,bool)</param> | |
/// <example> | |
/// string cssClsx1 = Utils.Clsx("d-flex pa-6", ("visible", f_show), ("hidden", !f_show)); | |
/// string cssClsx2 = Utils.Clsx("d-flex pa-6", f_show ? "visible" : "hidden"); | |
/// </example> | |
public static string Clsx(params object[] cssClassList) | |
{ | |
StringBuilder sb = new(); | |
foreach (var input in cssClassList) | |
{ | |
if (input is string) | |
{ | |
string className = ((string)input).Trim(); | |
if (!String.IsNullOrEmpty(className)) | |
sb.Append(className + " "); | |
} | |
else if (input is ValueTuple<string, bool>) | |
{ | |
var classObj = (ValueTuple<string, bool>)input; | |
if (classObj.Item2) | |
{ | |
string className = ((string)classObj.Item1).Trim(); | |
if (!String.IsNullOrEmpty(className)) | |
sb.Append(className + " "); | |
} | |
} | |
} | |
return sb.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment