【问题标题】:How to pass value of radio button to component in react如何将单选按钮的值传递给反应组件
【发布时间】:2021-12-10 20:29:25
【问题描述】:

我无法理解如何将选定单选按钮的值传递给 React 中的另一个组件。 我现在正在摆弄星球大战 API。尝试构建一个简单的 OPA,用户可以在其中获取有关 SW 世界中角色和地点的信息。

用户可以选择他想要的信息类型,例如搜索行星,然后输入所选行星的名称和其他信息。

我正在尝试结合单选按钮和文本输入来构建此功能。

我将文本输入和单选按钮放在两个不同的组件中——我如何让它们相互通信——或者换一种方式:

如何将一个单选按钮的值传递给将其添加到我要获取的 URL 的另一个组件?

我的单选按钮组件代码:

import { React, useState } from 'react';
import styled from 'styled-components';

import {
    FormControl,
    FormControlLabel,
    RadioGroup,
    Radio,
} from '@material-ui/core';

const ChooseOption = () => {
    const [selected, setSelected] = useState('films');

    const isButtonSelected = (value) => {
        if (selected === value) {
            return true;
        }
    };

    const handleChange = (e) => {
        setSelected(e.target.value);
    };

    return (
        <Container>
            <FormControl component="fieldset">
                <RadioGroup
                    className="radio-group"
                    row
                    aria-label="star wars ressource"
                    name="row-radio-buttons-group"
                    value={selected}
                >
                    <FormControlLabel
                        value="films"
                        control={<Radio />}
                        label="Films"
                        checked={isButtonSelected('films')}
                        onChange={handleChange}
                    />
                    <FormControlLabel
                        value="people"
                        control={<Radio />}
                        label="People"
                        checked={isButtonSelected('people')}
                        onChange={handleChange}
                    />
                    <FormControlLabel
                        value="planets"
                        control={<Radio />}
                        label="Planets"
                        checked={isButtonSelected('planets')}
                        onChange={handleChange}
                    />
                    <FormControlLabel
                        value="species"
                        control={<Radio />}
                        label="Species"
                        checked={isButtonSelected('species')}
                        onChange={handleChange}
                    />
                    <FormControlLabel
                        value="starships"
                        control={<Radio />}
                        label="Starships"
                        checked={isButtonSelected('starships')}
                        onChange={handleChange}
                    />
                    <FormControlLabel
                        value="vehicles"
                        control={<Radio />}
                        label="Vehicles"
                        checked={isButtonSelected('vehicles')}
                        onChange={handleChange}
                    />
                </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;
        }
    }
`;

我的表单组件代码,由单选按钮组件和文本输入组成:

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('');
    const [selected, setSelected] = useState();
    const [data, setData] = useState([]);

    const handleChange = (e) => {
        setSearch(e.target.value);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
    };

    const handleRadio = (e) => {
        setSelected(e.target.value);
        console.log(selected);
    };
    // const searchForRessource = () => {
    //     fetch(baseURL + search)
    //         .then((response) => {
    //             return response.json();
    //         })
    //         .then((data) => console.log(data));
    // };
    useEffect(() => {
        fetch(baseURL)
            .then((response) => {
                return response.json();
            })
            .then((data) => setData(data));
    }, []);
    console.log(data);
    return (
        <>
            <Container>
                <form className="input-form" onSubmit={handleSubmit}>
                    <ChooseOption onChange={handleRadio} />
                    <input
                        className="text-input"
                        type="text"
                        id="item-input"
                        onChange={handleChange}
                        value={search}
                    />
                </form>
                <Button>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;
    }
`;

【问题讨论】:

    标签: javascript reactjs api material-ui radio-button


    【解决方案1】:

    您将 onChange 处理程序传递给您的 ChooseOption 组件,但从未调用它。您可以在 SearchItem 组件中保持单选按钮的状态(因为您已经有一个状态对象(已选中),或者您可以在 ChooseOption 内添加一个 useEffect 挂钩,每次您的 selected 调用 onChange状态在那里更新(或者更好的是在你的handleChange函数中:

    import { React, useState } from 'react';
    import styled from 'styled-components';
    
    import {
        FormControl,
        FormControlLabel,
        RadioGroup,
        Radio,
    } from '@material-ui/core';
    
    const ChooseOption = ({ onChange }) => { // define the passed onChange handler
        const [selected, setSelected] = useState('films');
    
        const isButtonSelected = (value) => {
            if (selected === value) {
                return true;
            }
        };
    
        const handleChange = (e) => {
            setSelected(e.target.value);
            onChange(e); // this fires the onChange handler (handleRadio) you passed in SearchItem
        };
    
        return (
            <Container>
                <FormControl component="fieldset">
                    <RadioGroup
                        className="radio-group"
                        row
                        aria-label="star wars ressource"
                        name="row-radio-buttons-group"
                        value={selected}
                    >
                        <FormControlLabel
                            value="films"
                            control={<Radio />}
                            label="Films"
                            checked={isButtonSelected('films')}
                            onChange={handleChange}
                        />
                        <FormControlLabel
                            value="people"
                            control={<Radio />}
                            label="People"
                            checked={isButtonSelected('people')}
                            onChange={handleChange}
                        />
                        <FormControlLabel
                            value="planets"
                            control={<Radio />}
                            label="Planets"
                            checked={isButtonSelected('planets')}
                            onChange={handleChange}
                        />
                        <FormControlLabel
                            value="species"
                            control={<Radio />}
                            label="Species"
                            checked={isButtonSelected('species')}
                            onChange={handleChange}
                        />
                        <FormControlLabel
                            value="starships"
                            control={<Radio />}
                            label="Starships"
                            checked={isButtonSelected('starships')}
                            onChange={handleChange}
                        />
                        <FormControlLabel
                            value="vehicles"
                            control={<Radio />}
                            label="Vehicles"
                            checked={isButtonSelected('vehicles')}
                            onChange={handleChange}
                        />
                    </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

    【讨论】:

    • 非常感谢您的帮助 - 现在它可以工作了。你是对的 - 在两个地方保持状态真的很烦人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2020-11-07
    • 1970-01-01
    • 2020-01-10
    • 2017-11-30
    • 2014-03-26
    相关资源
    最近更新 更多