React中如何将单选按钮(radio button)的选中值传递给其他组件
解决方案
核心逻辑
通过props回调的方式实现子组件到父组件的通信:父组件将值更新函数通过props传给单选按钮子组件,子组件选中值变化时调用该函数,将选中值同步到父组件state,父组件即可直接用该值拼接请求URL。
具体修改步骤
1. 修改单选按钮子组件 ChooseOption.js
- 移除内部冗余的
selected状态,改为接收父组件传入的选中值和变更回调 - 统一在
RadioGroup上绑定变更事件,简化代码
修改后的完整代码:
import React from 'react'; import styled from 'styled-components'; import { FormControl, FormControlLabel, RadioGroup, Radio, } from '@material-ui/core'; // 接收父组件传入的props: value(当前选中值)、onChange(值变更回调) const ChooseOption = ({ value, onChange }) => { return ( <Container> <FormControl component="fieldset"> <RadioGroup className="radio-group" row aria-label="star wars ressource" name="row-radio-buttons-group" value={value} // 选中值变化时调用父组件传入的回调 onChange={onChange} > <FormControlLabel value="films" control={<Radio />} label="Films" /> <FormControlLabel value="people" control={<Radio />} label="People" /> <FormControlLabel value="planets" control={<Radio />} label="Planets" /> <FormControlLabel value="species" control={<Radio />} label="Species" /> <FormControlLabel value="starships" control={<Radio />} label="Starships" /> <FormControlLabel value="vehicles" control={<Radio />} label="Vehicles" /> </RadioGroup> </FormControl> </Container> ); }; export default ChooseOption; const Container = styled.div` text-align: center; .radio-group { width: 85%; margin: auto; color: white; } .MuiFormControlLabel-root { display: grid; margin: 1rem 1.5rem; .MuiButtonBase-root { background-color: #000; } } `;
2. 修改父组件 SearchItem.js
- 给
selected状态设置默认值,和单选按钮初始选中值对齐 - 将
selected和值更新函数传给子组件 - 补充提交逻辑,用
selected和搜索关键词拼接请求URL
修改后的完整代码:
import React, { useState, useEffect } from 'react'; import styled from 'styled-components'; import { baseURL, appendix, routeObject } from '../api'; import { Button } from '@material-ui/core'; import ChooseOption from './ChooseOption'; const SearchItem = () => { const [search, setSearch] = useState(''); // 设置默认选中值为films const [selected, setSelected] = useState('films'); const [data, setData] = useState([]); const handleChange = (e) => { setSearch(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); // 拼接请求URL,星球大战API搜索格式为 baseURL/资源类型?search=关键词 const requestUrl = `${baseURL}/${selected}?search=${encodeURIComponent(search)}`; // 发起请求逻辑 fetch(requestUrl) .then(res => res.json()) .then(res => { console.log('查询结果:', res); // 后续处理查询结果逻辑 }) }; const handleRadio = (e) => { setSelected(e.target.value); }; useEffect(() => { fetch(baseURL) .then((response) => { return response.json(); }) .then((data) => setData(data)); }, []); console.log(data); return ( <> <Container> <form className="input-form" onSubmit={handleSubmit}> {/* 传入当前选中值和变更回调给子组件 */} <ChooseOption value={selected} onChange={handleRadio} /> <input className="text-input" type="text" id="item-input" onChange={handleChange} value={search} placeholder="输入搜索关键词" /> </form> <Button type="submit" form="input-form">Search</Button> </Container> </> ); }; export default SearchItem; const Container = styled.div` .input-form { margin: 2rem auto; text-align: center; .text-input { background-color: var(--starWarsYellow); width: 70%; border: none; padding: 0.75rem; color: #000; border-radius: 3px; } .text-input:focus { outline: none; } } .MuiButtonBase-root { background-color: var(--starWarsYellow); width: 45%; display: block; margin: auto; } .MuiButtonBase-root:active { background-color: green; } `;
内容的提问来源于stack exchange,提问作者Daniel Juergens
相关产品推荐
相关产品推荐

