簡體   English   中英

如何在 React 中的兩個組件之間傳遞變量?

[英]How can I pass a variable between two components in React?

我在 React 中有一個表單組件,用於將數據發送到 pg 數據庫。

這是我的表單腳本:

import bodyParser from 'body-parser';
import React, { Fragment, useState } from 'react';
import RatingStar from '../components/rating'

const InputData = () => {
    
    const [name, setName] = useState('')
    const [rating, setRating] = useState('')

    const onSubmitForm = async(e) => {
        e.preventDefault();
        try {
            const payload = {
                name,
                rating
            }

            const response = await fetch("path", {
                method:"POST",
                headers:{"Content-Type":"application/json"},
                body:JSON.stringify(payload)
            });
            window.location = "/";
        } catch (error) {
            console.log(error.message);
        }
    }

    return(
        <Fragment>
            <div className="container">
                <h1 className="text-center mt-5">RATE</h1>
                <form className="mt-5" onSubmit={onSubmitForm}>
                    <div className="form-group">
                        <input 
                            placeholder="Name"
                            type='text' 
                            className='form-control' 
                            value={name} 
                            onChange={e => setName(e.target.value)}
                        />
                    </div>
                    <div className="form-group">
                        <div>
                            <RatingStar
                                value={}
                            />
                        </div>
                    </div>
                    <div className="d-flex justify-content-center">
                        <button type="submit" className="d-flex btn btn-primary">Submit</button>
                    </div>
                </form>
            </div>

        </Fragment>
    );
}

export default InputData;

這是我的評分部分:

import React, { useState } from 'react';
import { render } from 'react-dom';
import ReactStars from 'react-rating-stars-component'
import './style.css'


export default function RatingStar() {
  
  const [rating, setRating] = useState("")  

  const secondExample = {
    size: 50,
    count: 5,
    color: "black",
    activeColor: "yellow",
    value: 0,
    a11y: true,
    isHalf: true,
    emptyIcon: <i className="far fa-star" />,
    halfIcon: <i className="fa fa-star-half-alt" />,
    filledIcon: <i className="fa fa-star" />,
    onChange: (newValue) => {
      console.log(`Example 2: new value is ${newValue}`);
      setRating(newValue) // my try
    }
  };
  return (
    <div className="starComponent">
      <ReactStars {...secondExample}
       />
    </div>
  );
}

所以我想知道如何在表單組件中使用newValue

現在,我嘗試在評級組件中使用 useState,但我無法從表單組件訪問它以在我的 Paylod 中使用它。

不要在兩個組件中保留相同的 state(即評級值),而是將其保留在表單組件中並將其作為道具傳遞給評級組件。

每當通過調用 function 更改值時,評級組件將通知父(表單)組件。 這稱為將state 向上提升

這是 Rating 組件的代碼,它從表單組件中獲取ratingonRatingChange道具。 onRatingChange將使用來自onChange function 內部的newValue調用。

export default function RatingStar({ rating, onRatingChange }) {
  const secondExample = {
    size: 50,
    count: 5,
    color: "black",
    activeColor: "yellow",
    value: rating, // pass rating value here
    a11y: true,
    isHalf: true,
    emptyIcon: <i className="far fa-star" />,
    halfIcon: <i className="fa fa-star-half-alt" />,
    filledIcon: <i className="fa fa-star" />,
    onChange: (newValue) => {
      console.log(`Example 2: new value is ${newValue}`);
      // call onRatingChange function with new rating value
      onRatingChange(newValue);
    }
  };
  return (
    <div className="starComponent">
      <ReactStars {...secondExample} />
    </div>
  );
}   

這是表單組件的代碼。

const InputData = () => {
    const [name, setName] = useState('')
    const [rating, setRating] = useState(0)

    const onSubmitForm = async(e) => {
        e.preventDefault();
        try {
            const payload = {
                name,
                rating
            }

            const response = await fetch("path", {
                method:"POST",
                headers:{"Content-Type":"application/json"},
                body:JSON.stringify(payload)
            });
            window.location = "/";
        } catch (error) {
            console.log(error.message);
        }
    }

    return(
        <Fragment>
            <div className="container">
                <h1 className="text-center mt-5">RATE</h1>
                <form className="mt-5" onSubmit={onSubmitForm}>
                    <div className="form-group">
                        <input 
                            placeholder="Name"
                            type='text' 
                            className='form-control' 
                            value={name} 
                            onChange={e => setName(e.target.value)}
                        />
                    </div>
                    <div className="form-group">
                        <div>
                            <RatingStar
                                rating={rating}
                                onRatingChange={(newRating)=>{
                                  // update rating value here when you get a new value
                                  setRating(newRating);
                                }}
                            />
                        </div>
                    </div>
                    <div className="d-flex justify-content-center">
                        <button type="submit" className="d-flex btn btn-primary">Submit</button>
                    </div>
                </form>
            </div>

        </Fragment>
    );
}

export default InputData;

您需要將 state 保留在InputData中,並使用更改處理程序將其傳遞給RatingStar

const InputData = () => {
  const [rating, setRating] = useState(0);
  const handleRatingChange = (newRating) => {
    console.log(`setting rating to ${newRating}`);
    setRating(newRating);
  }

  return (
    <RatingStar value={rating} onChange={handleRatingChange} />
  );
};

然后RatingStar只使用其父級的值。

const RatingStar = ({ value, onChange }) => {
  const otherProps = {};
  return (
    <ReactStars {...otherProps} value={value} onChange={onChange} />
  );
};

在這里, RatingStar是一個受控組件

暫無
暫無

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

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