当在"是";它正在激活div,但我无法实现的是,如果我激活单选按钮";否";div是隐藏的。
import { useState } from "react";
export default function Pruebas() {
const [value2, setValue2] = useState("")
return (
<div>
<div className="col-sm-6">
<div className="form-check">
<input className="form-check-input" type="radio" name="radio1" value="no" checked onChange={e => setValue2(e.currentTarget.value)} />
<label className="form-check-label">NO</label>
<input className="form-check-input" type="radio" value="si" name="radio1"
onChange={e => setValue2(e.currentTarget.value)} />
<label className="form-check-label">SI</label>
</div>
</div>
<div className="col-sm-7">
{ value2==='si' ? (<div className="card">
<div className="card-body">
<h1>DIV OK</h1>
</div>
</div>
):null}
</div>
要使no作为您的初始单选值,您可以在useState中设置默认值。根据状态值添加选中的属性。你的代码看起来像
import { useState } from "react";
export default function Test() {
const [value2, setValue2] = useState("no");
return (
<>
<div className="col-sm-6">
<div className="form-check">
<input
className="form-check-input"
type="radio"
name="radio1"
value="no"
checked={value2 === "no"}
onChange={(e) => setValue2(e.currentTarget.value)}
/>
<label className="form-check-label">NO</label>
<input
className="form-check-input"
type="radio"
value="si"
name="radio1"
checked={value2 === "si"}
onChange={(e) => setValue2(e.currentTarget.value)}
/>
<label className="form-check-label">SI</label>
</div>
</div>
<div className="col-sm-7">
{value2 === "si" && (
<div className="card">
<div className="card-body">
<h1>DIV OK</h1>
</div>
</div>
)}
</div>
</>
);
}
只需删除已检查";在">onChange";从第一无线电输入。
<input className="form-check-input" type="radio" name="radio1" value="no" onChange={e => setValue2(e.currentTarget.value)} />
<label className="form-check-label">NO</label>
Checked不允许value2更改其值。