Basic React form submit refreshes entire page

前端 未结 2 1846
忘掉有多难
忘掉有多难 2021-01-04 11:58

I\'m trying to create an input form that stores information in a component\'s state variable, then outputs that variable on the screen. I read the docs on controlled compone

相关标签:
2条回答
  • 2021-01-04 12:40

    Prevent the default behaviour:

    afterSubmission(event) {
        event.preventDefault();
        let name = this.state.itemName;
        this.setState ({
            storedItemName:this.state.itemName
        }, function() {
            alert(this.state.storedItemName); // Shows the right value!
        });
    }
    
    0 讨论(0)
  • 2021-01-04 12:50

    Just call event.preventDefault method to prevent default behavior of form

    afterSubmission(event) {
        event.preventDefault();
        let name = this.state.itemName;
        this.setState ({
            storedItemName:this.state.itemName
        }, function() {
            alert(this.state.storedItemName); // Shows the right value!
        }
    }
    
    0 讨论(0)
提交回复
热议问题