例如,假设您有一个包含选择框的表单,并且您希望根据选择框的值更改要显示的组件。
<video controls autoplay loop muted>
<source src="images/video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
然后,我想根据上面作为 SecondElement 属性传递的值来切换要显示的元素。
<form onSubmit={handleOnSubmit}>
<label>
Type:
<select value={type} onChange={(e) => handleOnChange(e.target.value)}>
<option></option>
<option value={1}>First</option>
<option value={2}>Second</option>
<option value={3}>Third</option>
</select>
</label>
<SecondElement type={type} />
<input type="submit" value="Submit" />
</form>
然后我找回了标题中提到的错误:
export default function SecondElement({ type }: any) {
return (
<>
{
{
1: <FirstElem />,
2: <SecondElem />,
3: <ThirdElem />,
}[type]
}
</>
)
}
不过,我不知道如何解决这个问题,因此非常感谢您的帮助。
答案 0 :(得分:0)
你很接近。您所要做的就是限制参数类型(键)的类型。在您的情况下,它必须是数字,因为您在示例中使用的键都是数字。
export default function SecondElement( { type } : { type: number } ) {
return (
<>
{
{
1: <FirstElem />,
2: <SecondElem />,
3: <ThirdElem />,
}[type]
}
</>
)
}
更高级的版本是同时支持数字键和字符串键的版本。 options 参数是您的对象,具有不同的选择。
export default function SecondElement<T extends string|number>( { type } : { type: T }, options : any ) {
return options[type]
}