是否可以使按钮或文本区域之类的东西成为组件代码的一部分,然后在您想要使用该组件时将其省略?
Is it possible to make things like buttons or text areas be part of the component code but then be omit when you want to use that component?
我有这个我创建的表单组件,但在某些情况下我希望它有一个按钮,而在其他情况下我希望它有一个文本字段而不是我编写的输入字段。
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 个不同的组件?
是的,你可以在道具中提供你的条件,然后根据收到的道具显示右键:
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>
);
}
所以你将在第二个上有按钮,在第三个上有标签
您可以发送道具来决定显示什么
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
我有这个我创建的表单组件,但在某些情况下我希望它有一个按钮,而在其他情况下我希望它有一个文本字段而不是我编写的输入字段。
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 个不同的组件?
是的,你可以在道具中提供你的条件,然后根据收到的道具显示右键:
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>
);
}
所以你将在第二个上有按钮,在第三个上有标签
您可以发送道具来决定显示什么
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