我在 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 中使用它。
最佳答案
与其在两个组件中保持相同的状态(即评分值),不如将其保存在表单组件中并将其作为 prop 传递给评分组件。
每当通过调用函数更改值时,评级组件将通知父(表单)组件。这叫做 Lifting state up .
这是 Rating 组件的代码,它从表单组件获取 rating
和 onRatingChange
属性。 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>
);
}
这是Form组件的代码。
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;
关于javascript - 如何在 React 中的两个组件之间传递变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67878197/