我正在做一个简短的测验。每个问题都有四个选项,每个选项最后都会与可能的结果相关联。我跟踪选择的选项的方式是保持我的状态。请参阅下面的代码以获得澄清。
import React, { Component } from 'react';
import './App.css';
import Form from './components/Form';
class App extends Component {
constructor (props) {
super (props);
this.state = {
collaborator: 0,
pilot: 0,
producer: 0,
harmonizer: 0,
answers: [
{answer: 'Team building', archetype: 'collaborator'},
{answer: 'Directing strategy', archetype: 'pilot'},
{answer: 'Driving task completion', archetype: 'producer'},
{answer: 'Ensuring long term stability and quality of work',
archetype: 'harmonizer'}
]
}
this.onSelect = this.onSelect.bind(this);
}
onSelect(e) {
switch (e.target.value) {
case 'collaborator':
this.setState(prevState => {
return {collaborator: prevState.collaborator ++}
});
break;
case 'pilot':
this.setState(prevState => {
return {pilot: prevState.pilot ++}
});
break;
case 'producer':
this.setState(prevState => {
return {producer: prevState.producer ++}
});
break;
case 'harmonizer':
this.setState(prevState => {
return {harmonizer: prevState.harmonizer ++}
});
break;
}
}
render() {
return (
<div>
<Form answers={this.state.answers} onSelect={this.onSelect}/>
</div>
);
}
}
export default App;
这是我的Form组件的组件,它正在从App接收道具。
import React from 'react';
import PropTypes from 'prop-types';
import { RadioGroup, RadioButton } from 'react-radio-buttons';
function Form (props) {
return (
<RadioGroup onSelect={props.onSelect}>
{
props.answers.map(answer =>
<RadioButton key={answer.answer} value={answer.archetype}>
{answer.answer}
</RadioButton>
)
}
</RadioGroup>
)
}
Form.propTypes = {
answers: PropTypes.array.isRequired,
onSelect: PropTypes.func.isRequired
};
export default Form;
我遇到的问题是,当我在浏览器中运行应用程序并查看我的开发工具中的状态时,单击选项似乎不会更新状态。我猜这个问题出现在我onSelect
App
内的row
函数中?我做了一点挖掘,但似乎无法自己找到解决方案。非常感谢任何帮助。
答案 0 :(得分:0)
你在这里遇到了几个问题:
RadioGroup
accepts onChange
和不 onSelect
。
<RadioGroup onChange={props.onSelect}>
它将返回value
和不 event
onSelect(value) {
switch (value) {
case 'collaborator':
this.setState(prevState => {
return { collaborator: prevState.collaborator + 1 }
});
break;
您正在使用此行直接改变状态:
return { collaborator: prevState.collaborator++ }
将其更改为:
return { collaborator: prevState.collaborator + 1 }