I am unable to change state with button with onsen-ui - please

69 Views Asked by At

I am learning Onsen-ui React and button to reset state is not working.

See below a simple test case

´´´

class MyApp extends Component {

constructor(props) {
super(props);
this.state = { myVal: 123 };
}

clickTest() {
this.setState({ myVal:456 });
}

render() {
return (
<Page>
<div id="test">{this.state.myVal}</div>
<ons-button onClick="clickTest()">test</ons-button>
<ons-button onPress={() => { this.setState({ myVal:999}); }}>test</ons-button>
</Page>
);
}
}
My kidney for a good answer ;-) its bugging me for days

I want to change the state of myVal with ons-button and react
1

There are 1 best solutions below

0
On

There are a few problems with this code:

  • Your constructor should bind this for the clickTest function: this.clickTest = this.clickTest.bind(this);
  • The syntax for onClick is onClick={this.clickTest} not onClick="clickTest()".
  • onPress is not a valid ons-button prop; it should be onClick.

This is the fixed code:

class MyApp extends Component {

  constructor(props) {
    super(props);
    this.state = { myVal: 123 };
    this.clickTest = this.clickTest.bind(this);
  }
  
  clickTest() {
    this.setState({ myVal:456 });
  }
  
  render() {
    return (
      <Page>
        <div id="test">{this.state.myVal}</div>
        <ons-button onClick={this.clickTest}>test</ons-button>
        <ons-button onClick={() => { this.setState({ myVal:999}); }}>test</ons-button>
      </Page>
    );
  }
}

One kidney please.

Reference