Created
May 14, 2015 16:16
-
-
Save pthrasher/76825e602f19341d7cfe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************************************* | |
* Both of these examples use state * | |
*********************************************************************/ | |
var StatusParent = React.createClass({ | |
render: function() { | |
return ( | |
<Status/> | |
); | |
}, | |
}); | |
// long-form-example | |
var Status = React.createClass({ | |
getInitialState: function() { }, | |
onStatusChange: function(status) { | |
this.setState({ | |
currentStatus: status | |
}); | |
}, | |
componentDidMount: function() { | |
this.unsubscribe = statusStore.listen(this.onStatusChange); | |
}, | |
componentWillUnmount: function() { | |
this.unsubscribe(); | |
}, | |
render: function() { | |
return ( | |
<h1>this.state.currentStatus</h1> | |
); | |
} | |
}); | |
// shortest form | |
var Status = React.createClass({ | |
mixins: [Reflux.connect(statusStore,"currentStatus")], | |
render: function() { | |
return ( | |
<h1>this.state.currentStatus</h1> | |
); | |
} | |
}); | |
/********************************************************************* | |
* Functionally equivelent, but uses props: * | |
*********************************************************************/ | |
var StatusParent = React.createClass({ | |
render: function() { | |
return ( | |
<StoreConnection propName="currentStatus" store={statusStore}> | |
<Status /> | |
</StoreConnection> | |
); | |
}, | |
}); | |
var Status = React.createClass({ | |
render: function() { | |
return <h1>this.props.currentStatus</h1>; | |
} | |
}); | |
/********************************************************************* | |
* BUT HOW??? * | |
*********************************************************************/ | |
var StoreConnection = React.createClass({ | |
getInitialState() { | |
return { | |
storeData: null, | |
}; | |
}, | |
_handleStoreUpdate(storeData) { | |
this.setState({storeData: storeData}); | |
}, | |
_subscribeToStore() { | |
this.storeUnsubscribe = this.props.store.listen(this._handleStoreUpdate); | |
}, | |
_unsubscribeFromStore() { | |
this.storeUnsubscribe(); | |
}, | |
componentWillMount() { | |
this.unlisten = this.props.store.listen(this.handleStoreUpdate); | |
}, | |
render(){ | |
var child = React.children.only(this.props.children); | |
var extraProp = {}; | |
// clone our child, setting the propname to the state variable | |
// as they asked. | |
extraProp[this.props.propName] = this.state.storeData; | |
return React.cloneElement(child, extraProp); | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment