gpt4 book ai didi

javascript - Reactjs 动态表单获取错误 OnChange 输入值?

转载 作者:行者123 更新时间:2023-12-01 00:13:49 25 4
gpt4 key购买 nike

我在react.js中创建了一个动态表单,但我无法在输入中输入任何值,因为onchnage函数不起作用我不知道为什么我尝试了很多次,但我失败了,添加表单和删除表单工作正常,只是输入值不起作用,这里是我的代码和codesandbox链接https://codesandbox.io/s/reactdynamicform-02cho .

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";

class App extends Component {
constructor(props) {
super(props);
this.state = {
inputFields: [
{
firstName: "",
lastName: ""
}
]
};

}

handleAddFields = () => {
const values = this.state.inputFields;
values.push({ firstName: "", lastName: "" });
this.setState({
values
});
};

handleRemoveFields = index => {
const values = this.state.inputFields;
values.splice(index, 1);
this.setState({
values
});
};

async onChange(e, index) {
if (
["firstName","lastName"].includes(e.target.name)
) {
let cats = [...this.state.inputFields];
cats[index][e.target.name] = e.target.value;
await this.setState({
cats
});
}else{
this.setState({ [e.target.name]: e.target.value.toUpperCase() });
}
console.log(this.state.inputFields);
}

handleSubmit = e => {
e.preventDefault();
console.log("inputFields", this.state.inputFields);
};

render() {
return (
<>
<h1>Dynamic Form Fields in React</h1>
<form onSubmit={this.handleSubmit.bind(this)}>
<div className="form-row">
{this.state.inputFields.map((inputField, index) => (
<div key={`${inputField}~${index}`}>
<div className="form-group col-sm-6">
<label htmlFor="firstName">First Name</label>
<input
type="text"
className="form-control"
id="firstName"
name="firstName"
value={inputField.firstName}
onChange={this.onChange.bind(index)}
/>
</div>
<div className="form-group col-sm-4">
<label htmlFor="lastName">Last Name</label>
<input
type="text"
className="form-control"
id="lastName"
name="lastName"
value={inputField.lastName}
onChange={this.onChange.bind(index)}
/>
</div>
<div className="form-group col-sm-2">
<button
className="btn btn-link"
type="button"
onClick={() => this.handleRemoveFields(index)}
>
-
</button>
<button
className="btn btn-link"
type="button"
onClick={() => this.handleAddFields()}
>
+
</button>
</div>
</div>
))}
</div>
<div className="submit-button">
<button
className="btn btn-primary mr-2"
type="submit"
// onSubmit={this.handleSubmit}
>
Save
</button>
</div>
<br />
<pre>{JSON.stringify(this.state.inputFields, null, 2)}</pre>
</form>
</>
);
}
}

export default App;

最佳答案

你的做法不正确。使用对象包含表单值

state = { 
inputFields: { firstName: '', lastName: '' }
}


onChange = (e) => {
const { name, value } = e.target;

this.setState(prevState => ({ inputFields: { ...prevState.inputFields, [name]: value } }));
}


// in jsx

<input name="firstName" onChange={this.onChange} />

关于javascript - Reactjs 动态表单获取错误 OnChange 输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59904597/

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