我的输入字段有问题。我有五个。当我填满所有内容并按下按钮以在屏幕上显示它们时,所有位置仅显示我输入的最后一个...(很难表达,请问您是否不明白)
这是我想要输出的时间:
´´´
{this.state.new_array.map((char, i) => (
<li key={i}>
{`(${char.gender})
${char.name}
${char.height}
${char.eye_color}
${char.birth_year}`}
</li>
))}
´´´
这是我的输入字段和按钮:
´´´
<input onChange={this.handleChange}></input>
<input onChange={this.handleChange}></input>
<input onChange={this.handleChange}></input>
<input onChange={this.handleChange}></input>
<input onChange={this.handleChange}></input>
<button onClick={this.addNewCharacter} }>Add character</button>
´´´
这是我连接到按钮和输入的功能:
´´´
constructor(props){
super(props);
this.state = {
new_array: [],
nameFromInput: "",
heightFromInput: "",
birthyearFromInput: "",
genderFromInput: "",
eyecolorFromInput: ""
}
}
addNewCharacter = () => {
this.setState(oldState => ({
new_array: [...oldState.new_array, { // IM PRETTY SURE IT HAS TO DO WITH THIS FUCNTION?
name: this.state.nameFromInput,
height: this.state.heightFromInput,
birth_year: this.state.birthyearFromInput,
gender: this.state.genderFromInput,
eye_color: this.state.eyecolorFromInput
}]
}))
this.setState({showFavorites: true})
}
handleChange = event => {
this.setState({
nameFromInput: event.target.value,
heightFromInput: event.target.value,
birthyearFromInput: event.target.value,
genderFromInput: event.target.value,
eyecolorFromInput: event.target.value});
}
´´´
答案 0 :(得分:0)
每次更改输入字段的任何值时,您都在调用Base;Derived;
,每次都使用相同的函数,并且该输入更改Event作为参数传递。>
无论从哪个输入源触发此事件,该状态中的每个键都会使用该输入中的值进行更新。
可能看起来更好一些的东西是
this.handleChange
,您的输入将如下所示:
generateHandleChange = key => event => {
this.setState({[key]: event.target.value});
};
答案 1 :(得分:0)
为什么要使事情变得如此简单?
这里是Codesandbox https://codesandbox.io/s/serene-hodgkin-d5kz9?file=/src/App.js
中的一个有效示例为简洁起见,下面发布了解决方案:
import React from "react";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
height: "",
birthyear: "",
gender: "",
eyecolor: ""
};
}
handleChange = event => {
this.setState({
name: event.target.value,
height: event.target.value,
birthyear: event.target.value,
gender: event.target.value,
eyecolor: event.target.value
});
};
addNewCharacter = () => {
const { name, height, birth_year, gender, eye_color } = this.state;
this.setState({
new_array: {
name,
height,
birth_year,
gender,
eye_color
},
showFavorites: true
});
console.log(this.state);
};
render() {
return (
<div className="App">
<input onChange={this.handleChange} />
<input onChange={this.handleChange} />
<input onChange={this.handleChange} />
<input onChange={this.handleChange} />
<input onChange={this.handleChange} />
<button onClick={this.addNewCharacter}>Add character</button>
</div>
);
}
}