// In this example we pass one callbacks object through the components.// It makes it very easy to add new callbacks without updating the components in the chain// that don't need to access the new callbacks.classParentextendsReact.Component{_createItem=()=>console.log('Create')_updateItem=()=>console.log('Update')_deleteItem=()=>console.log('Delete')_callbacks=(component)=>{constcallbacks={ChildOne:{create:this._createItem,delete:this._deleteItem,update:this._updateItem,}}returncallbacks[component]||{}}render(){return(<ChildOnecreateCallback={this._createItem}deleteCallback={this._deleteItem}updateCallback={this._updateItem}/>)}}constChildOne=(props)=>{const{callbacks}=propsreturn(<div><ChildTwocallbacks={callbacks}/></div>)}ChildOne.propTypes={callbacks:PropTypes.object.isRequired,}constChildTwo=(props)=>{const{callbacks:{create,update,delete}}=propsreturn(<div><atabIndex="0"onClick={create}>Create</a><atabIndex="0"onClick={update}>Delete</a><atabIndex="0"onClick={delete}>Update</a></div>)}ChildTwo.propTypes={callbacks:PropTypes.shape({create:PropTypes.func.isRequired,update:PropTypes.func.isRequired,delete:PropTypes.func.isRequired,}).isRequired,}
// When passing a lot of callbacks things can get very messy quickly e.g.classParentextendsReact.Component{_createItem=()=>console.log('Create')_updateItem=()=>console.log('Update')_deleteItem=()=>console.log('Delete')render(){return(<ChildOnecreateCallback={this._createItem}deleteCallback={this._deleteItem}updateCallback={this._updateItem}/>)}}constChildOne=(props)=>{const{createCallback,deleteCallback,updateCallback}=propsreturn(<div><ChildTwocreateCallback={createCallback}deleteCallback={deleteCallback}updateCallback={updateCallback}/></div>)}ChildOne.propTypes={createCallback:PropTypes.func.isRequired,deleteCallback:PropTypes.func.isRequired,updateCallback:PropTypes.func.isRequired,}constChildTwo=(props)=>{const{createCallback,deleteCallback,updateCallback}=propsreturn(<div><atabIndex="0"onClick={createCallback}>Create</a><atabIndex="0"onClick={deleteCallback}>Delete</a><atabIndex="0"onClick={updateCallback}>Update</a></div>)}ChildTwo.propTypes={createCallback:PropTypes.func.isRequired,deleteCallback:PropTypes.func.isRequired,updateCallback:PropTypes.func.isRequired,}
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.