簡體   English   中英

如何將圖像包含到 Select 選項 label,React?

[英]How to include an image into a Select Option label, React?

我是 React 的新手,我正在嘗試創建一個帶有標簽中圖像的下拉列表,我正在使用 function 從 map 獲取值並構建一個 id: label 對以在下拉列表中顯示為選項。 其中id和label都是字符串類型。

我正在嘗試檢索這樣的選項:

const options = (): Select.Option[] => {
  return VALUES.map((color) => convertIdtoSelect(color));
};

其中,VALUES 的類型為:

export const VALUES: ValueDef[] = [
 {
   id: 'blue'
   name: 'Blue Color'
 },
 {
   id: 'red'
   name: 'Red color'
 },
];

這里的方法 convertIdtoSelect 看起來像:

export function convertIdtoSelect(color: ValueDef): Select.Option {
 return {
  id: color.id,
  label: `${color.name}` // Insert an image in this label that I have in a directory, before the name.
 };
}

請讓我知道我該怎么做。 我試過了:

label: `<div><img src={/img/src/${color.id}.png} height="30px" width="30px"/> ${color.name} </div>`,

這是行不通的。 請讓我知道我做錯了什么,並提前感謝您的幫助和建議。

由於它是 React,您可以將 JSX 直接傳遞到 object

export function convertIdtoSelect(color: ValueDef): Select.Option {
 return {
  id: color.id,
  label: <div><img src={`/img/src/${color.id}.png`} height="30px" width="30px">{color.name}</div> // Insert an image in this label that I have in a directory, before the name.
 };
}

然后使用{item.label}渲染它(假設item是從函數返回的變量)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM