簡體   English   中英

如何在反應中將單選按鈕的值傳遞給組件

[英]How to pass value of radio button to component in react

我無法理解如何將選定的單選按鈕的值傳遞給 React 中的另一個組件。 我目前正在擺弄 Star Wars 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;
    }
`;

您將一個 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM