我正处于学习反应的开始,我也需要从根组件到孩子的孩子采取状态。 我有App.js文件,该文件具有状态,即一组播放器。 然后得到Home.js,导入到App.js,然后有一个Players.js组件,需要显示该播放器对象。
/ * App.js * /
class App extends Component {
state = {
players: [
{name: 'Kacper', gender: 'M', id: 1},
{name: 'Patrycja', gender: 'F', id: 2},
{name: 'Marcel', gender: 'M', id: 3},
{name: 'Wiktoria', gender: 'F', id: 4}
]
}
deletePlayer = (id) => {
const players = this.state.players.filter(player => {
return player.id !== id
})
this.setState({
players
})
}
render(){
return (
<div>
<Home players={this.state.players} deletePlayer={this.deletePlayer}/>
</div>
);
}
}
export default App;
/ * Home.js * /
class Home extends Component {
state = {
players: players
}
render(){
return (
<div className="add-players">
<Players players={this.state.players}/>
<div className="add-player"></div>
<button className="start-btn">
<i className="material-icons">play_arrow</i> <p>Let's play!</p>
</button>
</div>
);
}
}
export default Home;
/ * Players.js * /
const Players = ({players, deletePlayer}) => {
const playerList = players.length ? (
players.map(player => {
return (
<div className="player" key={player.id}>
<div className="gender">{player.gender}</div>
<span>{player.name}</span>
<i className="material-icons" onClick={() => {deletePlayer(player.id)}}>close</i>
</div>
)
})
) : (
<p>Add player</p>
)
return (
<div className="players">
{playerList}
</div>
)
}
export default Players;
答案 0 :(得分:1)
您将根组件的播放器状态作为属性传递给Home
。因此,您必须从props
访问它。
只需将您的Home
组件更新为以下内容:
class Home extends Component {
render(){
return (
<div className="add-players">
<Players players={this.props.players}/>
<div className="add-player"></div>
<button className="start-btn">
<i className="material-icons">play_arrow</i> <p>Let's play!</p>
</button>
</div>
);
}
}
export default Home;