如何使用Reactjs在相同类型的两个组件之间共享道具(双向)? [英] How can I share props (two-ways) between two components of the same type with Reactjs?

查看:65
本文介绍了如何使用Reactjs在相同类型的两个组件之间共享道具(双向)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React构建音乐应用,而我是新手:)

I'm building a music app using React, and I'm a newbie :)

我的目标是

  • 加载JSON播放列表(格式为 JSPF )
  • 基于此JSON显示播放列表
  • 用播放列表曲目填充玩家的队列.

因此,我正在研究多个组件:轨道,轨道列表,播放列表和播放器.

So I'm working on several components : Track, Tracklist, Playlist, and Player.

  • 曲目列表中包含曲目.
  • 播放列表和播放器具有一个跟踪列表(及其他内容):播放器的队列是一个跟踪列表组件.
  • 播放器不是播放列表的后代,而是放在一边.例如,我希望能够将播放列表中的某些曲目排入队列(或取消排队)到播放器中.

我想要的是能够共享/同​​步播放列表和播放器之间(相同)音轨的道具:

假设我有一个最喜欢的道具来跟踪.
我将通过单击嵌套在轨道"组件中的按钮来切换它.如果我单击播放列表"中的按钮或播放器"中的按钮,则需要更新两个曲目的道具;反之亦然:所有道具都应该同步".

Let's say that I have a favorited prop for a Track.
I would toggle it by clicking a button nested in the Track component. I need to update the props of both tracks either if I click the button within the Playlist, or within the Player; and vice verca : all props should be "synced".

我可以用React来做到这一点吗?

Can I do this with React and how ?

非常感谢您的建议!

推荐答案

您应该拥有一个容器组件和其他组件(Track,Tracklist,Playlist和Player)作为容器组件的子代,容器组件可以将prop传递给子代和引用功能作为道具,因此可以拥有所有逻辑.

You should have a container component and other components (Track, Tracklist, Playlist, and Player) as children of container component, container component can pass props to children and refrence of functions as props, so can have all the logic.

您可以检查以下示例: https://github.com/upretim/thinking-in-react/

You can check this exmaple: https://github.com/upretim/thinking-in-react/

在此示例中,除App组件以外的所有组件均为哑/功能组件,App为智能/有状态或容器组件,其中包含所有逻辑和数据.在示例中,使用父组件在子组件之间共享filter的值.

In this example all the components except App component are dumb/ functional component, App is smart/ stateful or container component, which has all the logic and data. In the example value of filter is shared between child components using parent component.

这篇关于如何使用Reactjs在相同类型的两个组件之间共享道具(双向)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆