Reputation: 87
Good day. Could you say me how to access change state of some object on object click action from another object.
I have element Calculator which has set of Buttons and one Indicator. I wanna change Indicator's state on some Button clicked. For example increment indicator value if any button clicked;
<style>
#calculator table {
padding: 5px;;
border: ridge 3px;
}
#calculator table tr td {
text-align: center;
}
.nav-button, .nav-button button {
width: 100%;
}
.calc-indicator {
margin-bottom: 10px;
margin-top: 5px;
width: 100%;
}
.calc-indicator input {
border: solid 1px;
border-radius: 5px;
width: 93%;
padding: 4px;
text-align: right;
}
</style>
var Indicator = React.createClass({
getInitialState: function () {
return {
value: 0
}
},
render: function () {
return (
<div className="calc-indicator">
<input type="text" value={this.state.value}/>
</div>);
}
});
var Button = React.createClass({
buttonClicked: function () {
// here I wanna update Indicators state and render Indicator
},
render: function () {
return (
<div className="nav-button" id={this.props.digit}
onClick={this.buttonClicked.bind(this, "nav-button")}>
<button>{this.props.digit}</button>
</div>
);
}
});
var Calculator = React.createClass({
render: function () {
return (
<div id="calculator">
<table>
<tr>
<td colSpan="4">
<Indicator />
</td>
</tr>
<tr>
<td>
<Button digit="MC"/>
</td>
<td>
<Button digit="MR"/>
</td>
<td>
<Button digit="M+"/>
</td>
<td>
<Button digit="M"/>
</td>
</tr>
<tr>
<td>
<Button digit="BS"/>
</td>
<td>
<Button digit="CL"/>
</td>
<td>
<Button digit="C"/>
</td>
<td>
<Button digit="/"/>
</td>
</tr>
<tr>
<td>
<Button digit="7"/>
</td>
<td>
<Button digit="8"/>
</td>
<td>
<Button digit="9"/>
</td>
<td>
<Button digit="*"/>
</td>
</tr>
<tr>
<td>
<Button digit="4"/>
</td>
<td>
<Button digit="5"/>
</td>
<td>
<Button digit="6"/>
</td>
<td>
<Button digit="-"/>
</td>
</tr>
<tr>
<td>
<Button digit="1"/>
</td>
<td>
<Button digit="2"/>
</td>
<td>
<Button digit="3"/>
</td>
<td>
<Button digit="+"/>
</td>
</tr>
<tr>
<td colSpan="2">
<Button digit="0"/>
</td>
<td>
<Button digit="."/>
</td>
<td>
<Button digit="="/>
</td>
</tr>
</table>
</div>
);
}
});
React.render(<Calculator />, document.body);
If you know how to make code better, please, post your variants. Thank you for your time.
Upvotes: 0
Views: 200
Reputation: 2860
Move the state from Indicator to the Calculator. In the Button Class trigger this.props.add that is located in Calculator. So you have one Parent (Calculator) and 2 Childs (Button, Indicator).
Send the state down to the children
<Button add={this.add} /> and <Indicator value={this.state.value} />
Upvotes: 1