gpt4 book ai didi

reactjs - 提交表单后如何显示两种状态的结果

转载 作者:行者123 更新时间:2023-12-03 14:13:23 25 4
gpt4 key购买 nike

我有两个状态,INPUT1 和 INPUT2。我正在调用一个函数来用新值设置它们。然后我使用 const 值渲染结果。它很快就会被渲染而无需提交值。但是我想使用提交按钮来呈现结果。所以我试图创建结果状态并将值传递给它。但我需要帮助。我收到很多错误。

    import React, { Component } from 'react';
class AppComponent2 extends Component {

constructor(props) {
super(props);
this.state = {
input1: '',
input2 : ''
};

this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleInputChange(event) {
const target = event.target;
console.log(target); // event.target is saved in target.
const value = target.type === 'checkbox' ? target.checked : target.value;
console.log(value); //target.value is saved in value.
const name = target.name; //target.name is saved in name.
console.log(name);

this.setState({
[name]: value

});
}
handleSubmit(event) {
alert('This is input1: ' + this.state.input1);
alert('This is input2: ' + this.state.input2);
event.preventDefault();
}


render() {

const result = this.state.input1 && this.state.input2 ? parseInt(this.state.input1) + parseInt(this.state.input2) : null;
return (

<div class="jumbotron">
<h1 class="display-3">Add 2 Numbers</h1>
<hr class="my-4"/>

<fieldset>
<form onSubmit={this.handleSubmit}>
<label class="control-label" for="readOnlyInput"> </label>
<input value={this.state.input1} onChange={this.handleInputChange} class="form-control" id="input1" name="input1" type="text" placeholder="input here…" />
<input value={this.state.input2} onChange={this.handleInputChange} class="form-control" id="input2" name="input2" type="text" placeholder="input here…" />


</form>

</fieldset>

<p> This is the result {result} </p>

</div>




);
}
}

export default AppComponent2;

最佳答案

您正在 onChange 方法上设置状态,并在 result 变量中显示相同的状态。如果要在提交后显示,则需要在handleSubmit方法中setState并在render中显示。您可以执行以下操作:

handleInputChange(event) {
const target = event.target;
console.log(target); // event.target is saved in target.
const value = target.type === 'checkbox' ? target.checked : target.value;
console.log(value); //target.value is saved in value.
const name = target.name; //target.name is saved in name.
console.log(name);

this.setState({
[name]: value

});
}
handleSubmit(event) {
this.setState({val1: this.state.input1, val2: this.state.input2});
alert('This is input1: ' + this.state.input1);
alert('This is input2: ' + this.state.input2);
event.preventDefault();
}

然后在您的 render() 方法中,您可以定义变量,如下所示:

const result = this.state.val1 && this.state.val2 ? parseInt(this.state.val1) + parseInt(this.state.val2) : null;

关于reactjs - 提交表单后如何显示两种状态的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49533231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com