【问题标题】:setState did not work for UI change in React and MeteorsetState 不适用于 React 和 Meteor 中的 UI 更改
【发布时间】:2015-10-19 21:34:09
【问题描述】:

我正在尝试使用一个按钮来切换 UI 显示。当用户单击按钮时,它将显示相应的 UI。并且当用户再次点击时将其隐藏。我使用 setState 来切换“showItemBank”的值,但 UI 只显示一次,然后默认返回不可见。我错过了什么重要的事情吗?

这是我的应用程序使用 Meteor 和 React 的 jsx。

App = React.createClass ({

mixins: [ReactMeteorData],

getInitialState() {
    return {
      showItemBank: false
    }
},

onItemBankClick(event) {
    this.setState({
        showItemBank : ! this.state.showItemBank
    });

},

render() {
    var classItemBank = ""; 
    var classNewQuestion = ""; 
    if(this.state.showItemBank === false){ 
        classItemBank = "displayNone"; 
    } 
    if(this.state.showItemBank === true){ 
        classItemBank = "displayContent"; 
    }

    return (
        <div className="container">
            <header>
                <form className="new-task" >
                    <div>
                        <button onClick={this.onItemBankClick} className="menu">Select From the Item Bank</button>
                        <button className="menu">Add New Questions</button>
                    </div>
                    <div className={classItemBank}> Hi i am from ItemBank </div>    
                </form>

            </header>
        </div>
    );
}

  });

【问题讨论】:

    标签: javascript meteor reactjs setstate


    【解决方案1】:

    试试这个

    onItemBankClick(event) {
        event.preventDefault();
        this.setState({
            showItemBank : ! this.state.showItemBank
        });
    
    }
    

    按钮会默认尝试提交页面

    【讨论】:

    • 哇!有用!我实际上想过这个,但不要认为这会是问题。花了大约2个小时......很高兴我问了!谢谢!
    • @Lisa - 不要担心它会发生在我们最好的人身上......很高兴我能提供帮助......;)
    【解决方案2】:
    onItemBankClick(event) {
    
     // stop the event bubbling to parent, in this case <form>
     event.stopPropagation(); 
    
     // prevent default browser action
     event.preventDefault();
    
     this.setState({
        showItemBank : ! this.state.showItemBank
     });
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 2021-09-28
      • 2019-08-29
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2016-07-19
      • 2021-08-12
      相关资源
      最近更新 更多