我正在尝试使用挂钩和功能组件在子组件和父组件之间传递数据。
在我的父组件中,我有以下内容:-
import React, {useState} from "react"
import Card from './Card';
const CardsBoard = () => {
const { ratingObj, setRatingObj } = useState({});
console.log(ratingObj);
const cardInfo1 = {
.......
}
const cardInfo2 = {
.......
}
return (
<div className="container-fluid justify-content-center">
<div className="row">
<div className="col-md-6">
<div>
<h4>Player 1</h4>
</div>
<Card cardInfo={cardInfo1} onClick={() => setRatingObj(ratingObj)} />
</div>
<div className="col-md-6">
<h4>Player 2</h4>
<Card cardInfo={cardInfo2} onClick={() => setRatingObj(ratingObj)}/>
</div>
</div>
<div className="row top-buffer">
<div className="col-md-12 text-center">
<button id="startGameBtn" name="StartGameButton" className="btn btn-secondary">START GAME</button>
</div>
</div>
</div>
)
}
export default CardsBoard
然后在子组件中,我具有以下内容:-
import React from "react"
const Card = ({ cardInfo, onClick }) => {
return (
<div className="card text-center shadow">
<h4 className="card-title">{cardInfo.title}</h4>
<div className="overflow">
<img src={cardInfo.image} alt={cardInfo.image} className="card-image" />
</div>
<div className="card-body text-dark">
<div className="container-fluid justify-content-center card-rating-text">
{
cardInfo.ratings.map(row => (
<div className="row" key={row[0].title}>
<div className="col-md-4 text-left">{row[0].title}</div>
<div className="col-md-2 text-left card-rating-color" onClick={() => onClick(cardInfo.player, row[0].title, row[0].rating)} >{row[0].rating}</div>
<div className="col-md-4 text-left">{row[1].title}</div>
<div className="col-md-2 text-left card-rating-color" onClick={() => onClick(cardInfo.player, row[1].title, row[1].rating)}>{row[1].rating}</div>
</div>
))
}
</div>
</div>
</div>
)
}
export default Card
此刻我遇到错误:-
Uncaught TypeError: setRatingObj is not a function
at onClick (CardsBoard.js:58)
at onClick (Card.js:30)
如何将onClick对象从子对象传递给父对象?
感谢您的帮助和时间
答案 0 :(得分:1)
更改
const { ratingObj, setRatingObj } = useState({});
到
const [ ratingObj, setRatingObj ] = useState({});
useState
以[state,setStateFunc]的形式返回一个由两个元素组成的数组,因此您必须对其进行数组分解。