我有我創建的這個表單組件,但在某些情況下,我希望它有一個按鈕,而在其他情況下,我希望它有一個文本欄位,而不是我撰寫的輸入欄位。
function FormTypeOne(props) {
return (
<form className={classes.form}>
<div className={classes.control}>
<label htmlFor={"title"}>{props.title}</label>
<input type={props.type} required id={props.id} />
</div>
</form>
)
}
是否可以添加一個按鈕和一個文本欄位,然后決定我要使用哪個?還是我需要制作 3 個不同的組件?
uj5u.com熱心網友回復:
是的,您可以在道具中提供您的條件,然后根據收到的道具顯示正確的按鈕:
function FormTypeOne({case1, case2}) {
return (
<form className={classes.form}>
<div className={classes.control}>
<label htmlFor={"title"}>{props.title}</label>
<input type={props.type} required id={props.id} />
{case1 && <button />}
{case2 && <label />}
</div>
</form>
)
}
所以如果case1 = true,它將顯示按鈕,如果case2為true,它將顯示標簽
例如 :
function NewMeetupForm() {
return (
<Card>
{' '}
<FormTypeOne title="Meetup Title" />
<FormTypeOne title="Meetup Image" htmlFor="image" type="url" id="image" case1 />
<FormTypeOne title="Address" type="text" id="address" case2 />
</Card>
);
}
所以你會有第二個按鈕和第三個標簽
uj5u.com熱心網友回復:
你可以發送一個道具來決定展示什么
function FormTypeOne(props) {
const htmlElem = useMemo(() => props.isButton ?
<button /> :
<input type={props.type} required id={props.id} />
, [props.isButton])
return (
<form className={classes.form}>
<div className={classes.control}>
<label htmlFor={"title"}>{props.title}</label>
{htmlElem}
</div>
</form>
)
}
在這個例子中使用一個boolean道具isButton
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426572.html
標籤:javascript 反应 jsx 下一个
