我试图将一个简单的列表从父类传递给孩子,但“ props”始终为 undefined 。我在这里进行了研究,并尝试了几种方法,但结果始终相同:“未定义”。 在子类别状态下,如何获得分配给相应字段的卡片列表? (很明显,这是我的第一个React步骤)
游戏类(父级)
import React from "react";
import Hand from "./Hand/Hand";
let hand1 = [{ id: 1, value: 5 }, { id: 2, value: 4 }, { id: 3, value: 1 }];
export default class Game extends React.Component {
static initialState = () => ({
deckId: getDeckId
});
render() {
return (
<div className="container">
<div className="row">
<Hand cards={this.hand1} />
</div>
<br />
</div>
);
}
}
手部课程(儿童)
import React from "react";
import Card from "./../Card/Card";
const flipUp = card => {
this.setState(
prevState => ({
flippedCards: prevState.flippedCards.concat(card)
}),
this.sumCards()
);
};
const flipDown = card => {
this.setState(
prevState => ({
flippedCards: prevState.flippedCards.filter(c => c.id !== card.id)
}),
this.sumCards()
);
};
const CardList = props => {
return (
<div>
{props.cards.map(card => (
<Card key={card.id} flipUp={this.flipUp} flipDown={this.flipDown} />
))}
</div>
);
};
export default class Hand extends React.Component {
constructor(props) {
super(props);
console.log(props); //this is always undefined
this.state = {
cards: props.cards,
flippedCards: [],
currentSum: 0
};
}
sumCards = () => {
this.setState(prevState => ({
currentSum: prevState.flippedCards.reduce(
(acc, card) => card.value + acc,
0
)
}));
};
render() {
return (
<div className="row">
<div style={{ display: "inline-block" }}>
<CardList cards={this.state.cards} />
</div>
<div style={{ display: "inline-block" }}>{this.state.currentSum}</div>
</div>
);
}
}
答案 0 :(得分:3)
hand1
是在父类this
范围内未分配给Game
上下文的变量。您可以直接将其值用作prop值:
import React from 'react';
import Hand from './Hand/Hand';
let hand1 = [
{id: 1, value:5},
{id: 2, value:4},
{id: 3, value:1}
]
export default class Game extends React.Component {
static initialState = () => ({
deckId: getDeckId
});
render() {
return (
<div className="container">
<div className="row">
<Hand cards={hand1}/>
</div>
<br />
</div>
);
}
}
要能够按照您最初尝试的方式传递值,您应该在类构造函数中对其进行定义。
export default class Game extends React.Component {
constructor(props){
super(props);
this.hand1 = [
{id: 1, value:5},
{id: 2, value:4},
{id: 3, value:1}
];
}
static initialState = () => ({
deckId: getDeckId
});
render() {
return (
<div className="container">
<div className="row">
<Hand cards={this.hand1}/>
</div>
<br />
</div>
);
}
}