Inheriting State in react components
Ad
I'm trying to pass the state property 'val' down to the 'Counter' component and get 'Counter' to display its updated value when the mounted button is clicked. My problem is that I can pass the 'counterUpdate' function and call it from 'Counter', however I can't get the 'props.children' value to update within the view even though I'm updating 'state.val'. Any ideas and suggestions on why this might be would be much appreciated.
var App = React.createClass({
getInitialState: function(){
return {
val: 0
}
},
counterUpdate: function(){
this.setState(function(previousState, props){
return {
val: previousState.val + 1
}
})
},
mount: function(){
ReactDOM.render(<Counter cu={this.counterUpdate} >{this.state.val}</Counter>, document.getElementById('a'))
},
render: function(){
return (
<div>
<button onClick={this.mount}>MOUNT</button>
<div id="a"></div>
</div>
)
}
});
var Counter = React.createClass({
render: function(){
return (
<button onClick={this.props.cu}>{this.props.children}</button>
)
}
});
ReactDOM.render(<App />, document.getElementById('content'));
Ad
Answer
Ad
I don't know the specifics of why your code is not working, but calling ReactDOM.render inside a component is odd way to be handling this. I would probably do something like the following:
var App = React.createClass({
getInitialState: function(){
return {
val: 0,
showCounter: false,
}
},
counterUpdate: function(){
this.setState(function(previousState, props){
return {
val: previousState.val + 1
}
})
},
mount: function() {
this.setState({showCounter: true});
},
render: function(){
return (
<div>
<button onClick={this.mount}>MOUNT</button>
{
this.state.showCounter ? (<Counter cu={this.counterUpdate} >{this.state.val}</Counter>) : null
}
</div>
)
}
});
Ad
source: stackoverflow.com
Related Questions
Ad
- → Inheriting State in react components
- → How to make Laravel use my class instead of native PDO?
- → Decorators or subclassing is best pattern for React.Component
- → Model inheritance in OctoberCMS/Laravel (composite pattern)
- → javascript prototypical inheritance confused
- → Properties declared in constructor function vs prototype
- → ES6 multiple inheritance?
- → Table with multiple levels of inheritance - JQuery
- → Laravel model inheritance - how to call a function from parent model?
- → How does one programmatically 'open' a Material-UI Select field?
- → TypeScript function inheritance
- → How to use the __subclasscheck__ magic method?
- → Not working in Python 2, Python 2 vs Python 3 Inheriting a wrapper
Ad