如果我更新用户,我正在尝试更新子组件中表单中的值以发送到 api,但我无法更改表单中的任何值,并且如果我看到状态,它只会添加或删除一个字符。如何更新值?使用 defaultValue 解决了它,但它将输入更改为不受控制,这是我不想要的。
...
#Parent Class
import React from "react";
import "./styles.css";
import Child from "./child";
export default class Parent extends React.Component {
constructor() {
super();
this.state = {
user: {
id: [1, 2, 3, 4, 5],
name: ["john", "wick", "ellen", "fork", "gow"]
}
};
}
render() {
return <Child user={this.state.user}> </Child>;
}
}
#Child Class
import React from "react";
import "./styles.css";
export default class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {
id: "",
name: ""
}
};
}
handleSubmit = e => {
e.preventDefault();
};
handleChange = e => {
const data = { ...this.state.user };
data[e.currentTarget.name] = e.currentTarget.value;
this.setState({ user: data });
};
render() {
console.log(this.state);
console.log(this.props);
return (
<>
{this.props.user.id.map((id, index) => {
return (
<form onSubmit={this.handleSubmit}>
<label> id </label>
<input
type="text"
value={
this.props.user.id[index] !== "undefined"
? this.props.user.id[index]
: this.state.user.id
}
onChange={this.handleChange}
/>
<br />
<label> name </label>
<input
type="text"
value={
this.props.user.name[index] !== "undefined"
? this.props.user.name[index]
: this.state.user.name
}
onChange={this.handleChange}
/>
</form>
);
})}
}
</>
);
}
}
...
我的示例代码是
https://codesandbox.io/s/focused-shamir-y85v9?file=/src/parent.js:0