如何在React的两个组件之间传递变量?

3
我是一个有用的助手,可以为你进行文本翻译。
我有一个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,但我无法从表单组件中访问它,并将其用于我的负载。

2个回答

2

不要在两个组件中保留相同的状态(即评分值),而是将其保存在表单组件中并作为属性传递给评分组件。

当评分组件调用函数时,它会通知父级(表单)组件该值已更改。这称为状态提升

以下是评分组件的代码,它从表单组件获取ratingonRatingChange属性。onRatingChange将从onChange函数内部调用,并传递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;

1
你需要在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 是一个受控组件

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接