gpt4 book ai didi

javascript - 如何将状态用于多个值?

转载 作者:行者123 更新时间:2023-12-04 10:28:16 26 4
gpt4 key购买 nike

我试图在我的 Add Customer JS 中使用两种状态,一种用于隐藏表单,第二种用于 JSON。

我想使用 form-State 隐藏取消按钮单击时的表单和 JSON 的初始状态。

我想做这样的事情
Is it possible to have two states in one react component

import React from 'react';
import { Button, Form, Modal } from 'semantic-ui-react';

export default class AddCustomer extends React.Component {

constructor(props) {
super(props);
this.state = {
showCreateForm:false,
formData:{
name: '',
address: ''
}
}
this.handleChangeName = this.handleChangeName.bind(this);
this.handleChangeAddress = this.handleChangeAddress.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChangeName(event) {
const value = event.target.value;

console.log(value);

this.setState({formData:{name:value}});

//name: ""
//address: ""
console.log(this.state.formData);
}

handleChangeAddress(event) {
const value = event.target.value;
console.log(value);
this.setState({formData:{address:value}});

//name: "ram" but now there is no address in formData
console.log(this.state.formData);
}

handleSubmit(event) {
event.preventDefault();

////address: "aaaaa" now there no name in formData
console.log(this.state.formData);

this.setState({formData:{
name:this.state.name, address:this.state.address
}});
this.props.onAddFormSubmit(this.state.formData);
}

//On cancel button click close Create user form
closeCreateForm = () => {
this.setState({ showCreateForm: false })
}

//Open Create new Customer form
openCreateCustomer = () => {
this.setState({ showCreateForm: true })
}

render() {

return (
<div>
<Modal closeOnTriggerMouseLeave={false} trigger={
<Button color='blue' onClick={this.openCreateCustomer}>
New Customer
</Button>
} open={this.state.showCreateForm}>
<Modal.Header>
Create customer
</Modal.Header>
<Modal.Content>
<Form onSubmit={this.handleSubmit}>

<Form.Field>
<label>Name</label>
<input type="text" placeholder ='Name' name = "name"
value = {this.state.name}
onChange = {this.handleChangeName}/>
</Form.Field>

<Form.Field>
<label>Address</label>
<input type="text" placeholder ='Address' name = "address"
value = {this.state.address}
onChange = {this.handleChangeAddress}/>
</Form.Field>
<br/>
<Button type='submit' floated='right' color='green'>Create</Button>
<Button floated='right' onClick={this.closeCreateForm} color='black'>Cancel</Button>
<br/>
</Form>

</Modal.Content>
</Modal>

</div>
)
}

}

最佳答案

您可以直接在构造函数上给出初始状态。例如

this.state ={showCreateForm: false, formModel:{name:'abc', address:'xyz'}}

是的,从技术上讲,您可以拥有多个状态变量。

关于javascript - 如何将状态用于多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60537090/

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