我如何在JSX内呈现基于三元操作符的SVG ?



我正在使用Stencil.js,但语法与React相似。

const iconSVG = <svg>...</svg>
return (
<button>
{this.icon ?
this.position === 'left'
? iconSVG `${this.label}`
: `${this.label} icon` 
: this.label}
</button>
);
这给了我一个错误:iconSVG is not a function
return (
<button>
{this.icon ?
this.position === 'left'
? <svg> ...</svg> `${this.label}`
: `${this.label} icon` 
: this.label}
</button>
);

由于this.label,这不起作用。只能有一个元素(value)。

return (
<button>
{this.icon ?
this.position === 'left'
? `${<svg> ...</svg>} `${this.label}`
: `${this.label} icon` 
: this.label}
</button>
);

这给了我[Object object]在按钮旁边的label

const iconSVG = () => <svg> ...</svg>
return (
<button>
{this.icon ?
this.position === 'left'
? iconSVG() `${this.label}`
: `${this.label} icon` 
: this.label}
</button>
);

这给了我一个错误:iconSVG(...) is not a function显然是因为JSX被先读取。

那么,我怎么做呢?我如何在JSX中渲染SVG?

您可以尝试:

return (
<button>
{this.icon && this.position === 'left' && <svg>...</svg>}
{this.label}
{this.icon && this.position !== 'left' && ' icon'}
</button>
);

因为要在表达式中指定多个项,所以需要使用数组:

# 1

render() {
const iconSVG = <svg></svg>;
return (
<button>
{this.icon ?
this.position === 'left'
? [iconSVG, this.label]
: `${this.label} icon`
: this.label}
</button>
);
}

# 2

render() {
return (
<button>
{this.icon
? this.position === 'left'
? [<svg> ...</svg>, this.label]
: `${this.label} icon`
: this.label}
</button>
);
}

#3和#2是一样的。

# 4

render() {
const iconSVG = () => <svg> ...</svg>;
return (
<button>
{this.icon
? this.position === 'left'
? [iconSVG(), this.label]
: `${this.label} icon`
: this.label
}
</button>
);
}

按如下方式使用svg。

export const IconSvg = () => {
return (
<svg>
...
</svg>
);
};

然后,与您的三元操作符一起使用。

import React from "react";
const isRed = true;
export const RedIconSvg = () => {
return (
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="red" />
</svg>
);
};
export const BlueIconSvg = () => {
return (
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="blue" />
</svg>
);
};
function App() {
return (
<div className="App">
{isRed ? <RedIconSvg/> : <BlueIconSvg/>}
</div>
);
}
export default App;

最新更新