这里是我在将内容呈现给html时试图传递的map函数,但是我在条件运算符的第3行中得到了, expected错误。在结束括号上,我得到了Unexpected token. Did you mean {‘}}or},为什么会这样呢?是因为语法原因吗?
{newMessages.map(function (item) {
return (
{ userId === item.event.sender ?
<div class="flex justify-start mb-4">
<div
class="ml-2 py-3 px-4 bg-blue-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white"
>
{item.event.content.body}
</div>
<img
src="https://source.unsplash.com/vpOeXr5wmR4/600x600"
class="object-cover h-8 w-8 rounded-full"
alt=""
/>
</div>
:
<div class="flex justify-end mb-4">
<img
src="https://source.unsplash.com/vpOeXr5wmR4/600x600"
class="object-cover h-8 w-8 rounded-full"
alt=""
/>
<div
class="ml-2 py-3 px-4 bg-gray-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white"
>
{item.event.content.body}
</div>
</div>}
)
}
)
}发布于 2022-08-21 15:29:28
在将一个{表达式内插到JSX中时,应该使用{--例如,<div>{someVariable}</div>。如果您不在JSX的上下文中,则使用{来分隔对象文字的开头。
由于您不在JSX上下文中,所以此时:
return (
{ userId === item.event.sender ?
^抛出一个错误。
在这里,您可以完全删除{并返回元素数组,而不需要在该级别上使用任何JSX。
{newMessages.map(function (item) {
return (
userId === item.event.sender ?如果每个映射项周围都有一些元素,例如:
{newMessages.map(function (item) {
return (
<div className="item-container">
{
userId === item.event.sender ?发布于 2022-08-21 15:33:45
下面的代码应该可以工作
{
newMessages.map(function (item) {
return userId === item.event.sender ? (
<div className="flex justify-start mb-4">
<div className="ml-2 py-3 px-4 bg-blue-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white">
{item.event.content.body}
</div>
<img
src="https://source.unsplash.com/vpOeXr5wmR4/600x600"
className="object-cover h-8 w-8 rounded-full"
alt=""
/>
</div>
) : (
<div className="flex justify-end mb-4">
<img
src="https://source.unsplash.com/vpOeXr5wmR4/600x600"
className="object-cover h-8 w-8 rounded-full"
alt=""
/>
<div className="ml-2 py-3 px-4 bg-gray-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white">
{item.event.content.body}
</div>
</div>
);
});
}你用的是额外的花括号
发布于 2022-08-21 15:35:10
你有一些语法错误。只需确保用圆括号()括住每个JSX块,并使用className属性而不是class,因为它是JavaScript中的保留关键字。
{newMessages.map((item) =>
userId === item.event.sender ? (
<div className="flex justify-start mb-4">
<div className="ml-2 py-3 px-4 bg-blue-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white">
{item.event.content.body}
</div>
<img
src="https://source.unsplash.com/vpOeXr5wmR4/600x600"
className="object-cover h-8 w-8 rounded-full"
alt=""
/>
</div>
) : (
<div className="flex justify-end mb-4">
<img
src="https://source.unsplash.com/vpOeXr5wmR4/600x600"
className="object-cover h-8 w-8 rounded-full"
alt=""
/>
<div className="ml-2 py-3 px-4 bg-gray-400 rounded-br-3xl rounded-tr-3xl rounded-tl-xl text-white">
{item.event.content.body}
</div>
</div>
)
)}https://stackoverflow.com/questions/73435764
复制相似问题