我正尝试在下面更新values.answerB中的状态。
当我尝试在Input.js中编写updateState函数时,我无法理解如何获取输入值并更新状态对象中的values.answerB状态。
我在做什么错了?
UserForm.js文件
state = {
step: 1,
values: [
{
section: "summary",
answers:
{
answerA: 1,
answerB: 13,
answerC: 6
}
},
{
section: "players",
answers:
{
answerE: 15,
answerF: 132,
answerG: 63
}
}
]
}
switch (step) {
default:
return (
<Start />
);
}
Start.js文件
render() {
const { values } = this.props;
return (
<Input
label={'Player name'}
value={ values.answerB }
/>
)
}
Input.js文件
export class Input extends Component {
// PROBLEM UPDATING THE STATE HERE!!
updateState = e => {
this.setState({ [input]: e.target.value });
};
render() {
return (
<input class="bootstrap-sample-class"
min="0"
type="number"
onChange={this.updateState}
/>
)
}
}
export default Input;
答案 0 :(得分:1)
export class Input extends Component {
// PROBLEM UPDATING THE STATE HERE!!
updateState = e => {
this.setState({ values[0].answers.answerB });
};
render() {
return (
<input class="bootstrap-sample-class"
min="0"
type="number"
onChange={this.updateState}
/>
)
}
}
export default Input;
答案 1 :(得分:0)
您的updateState
应该在UserForm组件中,并作为道具传递到Input
组件中。
答案 2 :(得分:0)
updateState = e => {
// [input] input here was neither declared nor initialized with any value
this.setState({ [input]: e.target.value });
};
UserForm.js文件
state = {
step: 1,
values: [
{
section: "summary",
answers:
{
answerA: 1,
answerB: 13,
answerC: 6
}
},
{
section: "players",
answers:
{
answerE: 15,
answerF: 132,
answerG: 63
}
}
]
}
switch (step) {
default:
return (
<Start />
);
}
UserForm.js文件
state = {
step: 1,
values: [
{
section: "summary",
answers:
{
answerA: 1,
answerB: 13,
answerC: 6
}
},
{
section: "players",
answers:
{
answerE: 15,
answerF: 132,
answerG: 63
}
}
]
}
updateState =(e,input) => { // <=== changes
this.setState({ [input]: e.target.value });
};
switch (step) {
default:
return (
<Start update={this.updateState}/> // changes
);
}
答案 3 :(得分:0)
尝试在UserFrom.js中使用onchange
Userform.js
state = {
step: 1,
values: [
{
section: "summary",
answers:
{
answerA: 1,
answerB: 13,
answerC: 6
}
},
{
section: "players",
answers:
{
answerE: 15,
answerF: 132,
answerG: 63
}
}
]
}
updateState = e => {
let data=[...this.state.values]
let copstate=[...data,{...this.state.values[answers],answerB: e.target.value}]
this.setState({ values: copstate});
};
switch (step) {
default:
return (
<Start changed={(e)=>updateState(e)}/>
);
}
Start.js
render() {
const { values } = this.props;
return (
<Input
label={'Player name'}
value={ values.answerB }
changed={props.changed}
/>
)
}
Input.js文件
export class Input extends Component {
// PROBLEM UPDATING THE STATE HERE!!
render() {
return (
<input class="bootstrap-sample-class"
min="0"
type="number"
onChange={props.changed}
/>
)
}
}
export default Input;