在三个组件之间传递道具

时间:2017-11-30 16:17:01

标签: reactjs

我需要根据活动设备(可以是iphone或ipad)显示数据。我有3个组件:App,DeviceCheck和Collection。设备检查是一个带有2个按钮,Iphone和iPad的组件。在Collection组件中,我正在解析外部文件中的数据,例如:

const applications = [
  {
    device: 'iPhone',
    icon: icon,
    title: 'title',
    descr: 'descr',
    category: 'Games',
    link: 'link-to-appstore',
    price: 0.99,
    purchases: true
  },
  {
    device: 'iPad',
    icon: icon2,
    title: 'title2',
    descr: 'descr2',
    category: 'Games',
    link: 'link',
    price: 1.99,
    purchases: false,
  }
]

App.js结构是:

<DeviceCheck />
<Collection />

如何在Collection组件中显示iPhone或iPad数据,具体取决于在DeviceCheck组件中单击了哪个按钮?

4 个答案:

答案 0 :(得分:3)

  1. 创建一个将回调传递给设备检查的组件。
  2. 使用此回调从设备检查更新容器的状态。
  3. 使用容器中的状态设置集合的道具。
  4. 这在React中很常见,并且是组合模式如何工作的基础。如果需要在两个组件之间共享数据,只需将它们放入容器中,然后将状态提升到父组件即可。这些组件通常称为容器,并且有大量文档。

    这是一个很好的起点:https://reactjs.org/docs/lifting-state-up.html

    粗略的布局就是这样的。

    class Container extends React.Component {
      constructor(props) {
        super(props);
    
        // Don't forget to bind the handler to the correct context
        this.changeDevice = this.changeDevice.bind(this);
      }
    
      changeDevice(device) {
        this.setState({device: device});
      }
    
      render() {
        return (
          <DeviceCheck btnCb={this.changeDevice} />
          <Collection device={this.state.device} />
        )
      }
    }
    

答案 1 :(得分:2)

  1. 维护名为App.js的{​​{1}}状态的变量。
  2. 在按钮的点击处理程序中,调用selectedDevice以修改状态中的setState()
  3. 使用selectedDeviceselectedDevice
  4. 中显示相应的数据

答案 2 :(得分:1)

您的问题有点宽泛,但您可以使用所选设备保留state个对象,并使用setState按钮点击<DeviceCheck />来设置所选设备。并且<Collection {...selectedDevice} />将使用状态对象作为输入。

答案 3 :(得分:1)

在App组件中,您可以将deviceType作为状态,并根据参数设置deviceType,此函数应作为props传递给DeviceCheck组件。单击DeviceCheck按钮中的按钮后,需要调用prop函数,并将相应的按钮类型作为参数。 deviceType状态应作为prop传递到Collection组件,并且基于prop值,Collection组件可以呈现相应的Device数据。希望这有帮助!