React实现点击提交按钮按选中单选按钮跳转对应页面的问题
解决思路
要实现点击提交按钮后才跳转的需求,我们只需要用state暂存用户的单选选择,再把跳转逻辑绑定到GO按钮的点击事件上即可,具体修改后的代码如下:
// 先导入useState import { useState } from 'react'; // 组件名首字母必须大写,和导出的Home保持一致 const Home = () => { // 新增state存储选中的性别,初始值为空 const [selectedGender, setSelectedGender] = useState(''); // 提交按钮点击跳转逻辑 const handleGo = () => { if (!selectedGender) { alert('请先选择性别'); return; } window.location.href = `/${selectedGender}`; // 如果你用的是React Router v6,可以替换为更符合React生态的跳转方式: // const navigate = useNavigate(); // navigate(`/${selectedGender}`); }; return ( <div className="content-page"> <div className="card-box pt-3"> <div className="card-body"> <Accordion defaultActiveKey="1"> <Accordion.Item eventKey="1"> <Accordion.Header>Gender page</Accordion.Header> <Accordion.Body> <Row> <Col className='col-md-4'> <label>Action</label><span style={{ color: "red", fontWeight: 'bold' }}> *</span> </Col> <Col> {/* 统一name为gender保证单选互斥,选中时更新state */} <Form.Check type="radio" name="gender" id="male" value="male" label="male" inline onChange={(e) => setSelectedGender(e.target.value)} /> </Col> <Col> <Form.Check type="radio" name="gender" id="female" value="female" label="female" inline onChange={(e) => setSelectedGender(e.target.value)} /> </Col> <Col> <div className="right"> {/* 给GO按钮绑定点击事件 */} <Button variant="primary" type="button" onClick={handleGo}> Go </Button> </div> </Col> </Row> </Accordion.Body> </Accordion.Item> </Accordion> </div> <div className="card-body"></div> </div> </div> ); }; export default Home;
关键修改说明
- 修复了原代码中两个单选框
name属性不一致的问题,统一为gender后才能实现互斥选中效果 - 移除了单选框上的直接跳转逻辑,改为选中时更新存储选中值的state
- 把跳转逻辑迁移到GO按钮的点击事件中,仅在用户点击提交后才执行跳转
- 新增了未选择性别时的提示逻辑,避免异常跳转
内容的提问来源于stack exchange,提问作者shabu shankar
相关产品推荐
相关产品推荐

