[英]React if statement in map inside JSX tag
I've the following function to build a tabbed items: 我有以下函数来构建选项卡式项:
function ConstructTabs(props) {
const tabs = props.tabs;
const makeTabs = tabs.map((tab, index) => {
<React.Fragment>
<input
className="input-tabs"
id={"tab" + index}
type="radio"
name="tabs"
{index === 0 ? checked : ""}
/>
<label for={"tab" + index}>{tab}</label>
</React.Fragment>
});
return (
<React.Fragment>
{makeTabs}
</React.Fragment>
);
}
I want to insert the checked property only when the index is 0, my problem is with the condition "{index === 0 ? checked : ""}" . 我想只在索引为0时插入checked属性,我的问题是条件为“{index === 0?checked:”“}” 。 Here is the error I'm getting:
这是我得到的错误:
Parsing error: Unexpected token, expected "..."
275 | type="radio"
276 | name="tabs"
> 277 | {index === 0 ? checked : ""}
| ^
278 | />
279 | <label for={"tab" + index}>{tab}</label>
280 | </React.Fragment>
Is there a way to fix it or have a better alternative? 有没有办法解决它或有更好的选择?
Using a checked
prop to a form field without an onChange
handler will render a read-only field. 使用已
checked
prop到没有onChange
处理程序的表单字段将呈现只读字段。 If the field should be mutable use defaultChecked
. 如果字段应该是可变的,请使用
defaultChecked
。
So you could do this: 所以你可以这样做:
defaultChecked={index===0}
checked
with no embellishments is a shortcut for checked={true}
. 没有装饰的
checked
是checked={true}
的快捷方式。 To make it sometimes true and sometimes false, you can do: 为了使它有时是真的,有时是假的,你可以这样做:
name="tabs"
checked={index===0}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.