如何解决使用单选按钮上的索引存储数组对象单击反应
如何在反应数组中以索引的升序存储单选按钮值?
let questions;
class App extends Component {
constructor(props) {
super(props);
this.state = {
btnDisabled: true,questions: [],};
this.changeRadioHandler = this.changeRadioHandler.bind(this);
this.submitHandler = this.submitHandler.bind(this);
}
changeRadioHandler = (event) => {
const qn = event.target.name;
const id = event.target.value;
let text = this.props.data.matrix.options;
let userAnswer = [];
for (let j = 0; j < text.length; j++) {
userAnswer.push(false);
}
const option = text.map((t,index) => ({
text: t.text,userAnswer: userAnswer[index],}));
const elIndex = option.findIndex((element,i) => element.text === id);
let options = [...option];
options[elIndex] = {
...options[elIndex],userAnswer: true,};
const question = {
id: event.target.value,qn,options,};
if (this.state.questions.some((question) => question.qn === qn)) {
questions = [
...this.state.questions.filter((question) => question.qn !== qn),question,];
} else {
questions = [...this.state.questions,question];
}
console.log(questions);
this.setState({ questions });
if (questions.length === text.length) {
this.setState({
btnDisabled: false,});
}
};
submitHandler = () => {
console.log("btn clkd",questions);
};
render() {
return (
<div class="matrix-bd">
{this.props.data.header_text && (
<div class="header-qn">
<h5>{this.props.data.header_text} </h5>
</div>
)}
{this.props.data.matrix && (
<div class="grid">
{this.props.data.matrix.option_questions.map((questions,j) => {
return (
<div class="rows" key={j}>
<div class="cell main">{questions.text}</div>
{this.props.data.matrix.options.map((element,i) => {
return (
<div class="cell" key={i}>
<input
type="radio"
id={"rad" + j + i}
name={questions.text}
value={element.text}
onChange={this.changeRadioHandler}
></input>
<label htmlFor={"rad" + j + i}>{element.text}</label>
</div>
);
})}
</div>
);
})}
</div>
)}
<div class="buttonsubmit text-right">
<button
type="button"
id="QstnSubmit"
name="QstnSubmit"
class="btn btn-primary"
disabled={this.state.btnDisabled}
onClick={this.submitHandler}
>
{this.props.labels.LBLSUBMIT}
</button>
</div>
</div>
);
}
}
export default App;
我已经添加了代码,其中数组相对于索引是无序的,我想使用qn(const qn = event.target.name;)对象对数组进行排序。就像,它是如何从数据库中发出的,同样应该以同样的顺序进入数据库。
解决方法
您可以使用sort()方法,然后使用带有两个参数的回调函数,并以升序返回它们,如下所示:
ans.sort((a,b) =>{return a-b});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。