【问题标题】:I am unable to change state with button with onsen-ui - please我无法使用 onsen-ui 按钮更改状态 - 请
【发布时间】:2021-07-11 22:17:06
【问题描述】:

我正在学习 Onsen-ui React,但重置状态的按钮不起作用。

看下面一个简单的测试用例

´´´

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

【问题讨论】:

    标签: onsen-ui onsen-ui2


    【解决方案1】:

    这段代码有几个问题:

    • 您的构造函数应该为clickTest 函数绑定thisthis.clickTest = this.clickTest.bind(this);
    • onClick 的语法是 onClick={this.clickTest} 而不是 onClick="clickTest()"
    • onPress 不是有效的 ons-button 道具;应该是onClick

    这是固定代码:

    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>
        );
      }
    }
    

    请一个肾。

    参考

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多