Sharing data between components in React

后端 未结 2 605
小鲜肉
小鲜肉 2021-01-14 03:16

I\'m developing an app using Meteor and React as view engine

Consider this diagram:

React hide component from another example

I need to change C2 com

相关标签:
2条回答
  • 2021-01-14 03:33

    I think it's perfect time for you to introduce some state to your app. Try Redux, it's awesome.

    0 讨论(0)
  • 2021-01-14 03:38

    You can use any publish/subscribe events library and then make your components listen to any event you need.

    For example:

    import React from 'react'
    import 'events' from 'eventPublishSubscribeLibrary'
    
    class Component2 extends React.Component {
      constructor (props) {
        super(props)
        this.toggleVisibility = this.toogleVisibility.bind(this)
        this.state = {
          visible = true
        }
      }
      componentDidMount () {
        events.subscribe('clicked-button', this.toogleVisibility)
      }
      toogleVisibility () {
        this.setState({
          visible: !this.state.visible
        })
      }
      render () {
        return visible && (
          <div>content</div>
        )
      }
    }
    
    const Component4 = () => (
      <button onClick={events.publish('clicked-button')}>Toggle Visibility</button>
    )
    

    You can find in this post by davidwalsh a simple implementation for a Pub/Sub JavaScript Object. Or you can search in npm for some other library.

    the "right" way

    This is the most simple implementation I can think of and for small projects it is a quick an easy solution that should work.

    Anyway, as far as the project will grow a bit you will start to have a lot of actions/reactions between your components. With every new component you'll add it'll get more complicated to track all of these relations between all your components. Here is where it comes handy to have the global state of your application stored in one single place, and that is one of the three principles that redux is based on: the single source of truth.

    0 讨论(0)
提交回复
热议问题