Share state in top level React components

十年热恋 提交于 2019-12-06 04:46:09
doronn

working with redux can help you share one state all over your app without thinking what data to pass and what not. if you want to pass data to child without redux you can like that:

<Dragbar someData=[1,2,3] />

and in your component you can use this data {this.props.someData}

look at react docs or in this video https://www.youtube.com/watch?v=dcCcZ1IWZ6w

If you just want to kick off with react without redux, you can do by sharing e.g. An Event Emitter or Subject from the rx library in order to pass events from ne component to the other. The idea is then to

  1. create the event mediator
  2. pass it to both components
  3. register with the event mediator such that upon a new message/event you can call setState accordingly.
Abdennour TOUMI

You can use Event Oriented Programming (pub/sub) to make communication among components which have not the same parent .

mufa does the job of event-driven .

I have an answer here with an exampe of MUFA and i will write below an example that meets exactly your requirements :

General Rules for React with Event-driven :

  1. publish (fire) : is called in events handlers.

  2. subscribe (on) : is called in componentDidMount.

  3. unsubscribe (off) : is called in componentWillUnmount

const {on, fire} = mufa; 


class App extends React.Component {

  state={input:""};

  componentDidMount() {
    on('dragbar_change_state', (...args) => {
       this.setState(...args);
     })
  }
  
  setStateAndFire() {
   fire('app_change_state',...arguments);
   super.setState(...arguments);  
  } 
  
  render() {
     return (<div>Dragbar is saying : " {this.state.input} "</div>)
  }
    
} 

class Dragbar extends React.Component{

  componentDidMount() {
    on('app_change_state', (...args) => {
       this.setState(...args);
    })
  }
   
  setStateAndFire() {
    this.setState(...arguments);  
    fire('dragbar_change_state',...arguments);

  } 

   handleKeyUp(event) {
     this.setStateAndFire({input: event.target.value});
   }

    render() {
     return (<div><input type="text" onKeyUp={this.handleKeyUp.bind(this)} placeholder="Write somthing here you will see it in App component" style={{fontSize:15, width: 400}} /></div>)
    } 
}



ReactDOM.render( 
    <App />,
    document.getElementById('root')
);
ReactDOM.render( 
    <Dragbar />,
    document.getElementById('offcanvas')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<script src="https://cdn.rawgit.com/abdennour/mufa/ddf78fd9/cdn/mufa-latest.min.js"></script>
<h3>App Mounted in Root</h3>
<div id="root" ></div>
<hr />
<h3>DragBar mounted in offcanvas</h3>
<div id="offcanvas" ></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!