开发者社区> 问答> 正文

如何更新元素映射数组中元素的状态?

我有两个数据对象和三个分层组件,或者在沙箱中这里。数据包含一个问题列表,每个问题的下方都有一个输入框,允许多个回答。然而,我不知道如何在输入对特定问题的回答后正确更新正确问题的状态。 index.js

import React from 'react'; import { render } from 'react-dom'; import

import React from 'react';
import { render } from 'react-dom';
import QA from './qa';
//parent of qa.js

const questions = [
  {id : 1,
  question: "where is the origin of chihuahua?"},
  {id : 2,
  question: "when does the great migration happen in Africa?"}
]

const answers = [
  {
    id : 1,
    id_question : 1,
    answer: "Mexico"
    },
  {
    id : 2,
    id_question : 1,
   answer: "Argentina"
  },
  {
    id : 3,
    id_question : 2,
    answer: "Apr"
    },
  {
    id : 4,
    id_question : 2,
    answer: "May"}
]

export default class App extends React.Component {
  state = {
    q : questions, 
    a : answers
    }

  handleSubmit = (val, index) => {
    alert('index',index)
    this.setState({
      ...this.state,
      a: [...this.state.a, {id_question: index, answer: val}]
    });
  }

  render() {
    console.log(this.state)
    return (
      questions.map((q, index) =>
        <QA 
          key={index} 
          question={q.question}
          onSubmit={this.handleSubmit}
          />
      )  
    )
  }
}


render(<App />, document.getElementById('root'));

qa.js

import React from 'react';
import Answer from './answer';
import  "./style.css"
//parent of answer.js

export default class QA extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      text: ""
    }
  }
  render() {
    const { question } = this.props
    const { text } = this.state
    return (
      <div class='qa-block'>
        <div>Question: {question}</div>
        <Answer onSubmit={this.props.onSubmit}/>
      </div>
    )
  }
}

answer.js

import React from 'react';

const styles = {
  backgroundColor: 'lightgray',
};

export default class Answer extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      text: ""
    }
  }
  render() {
    const { text } = this.state
    return (
      <div style={styles}>
        <h4>Answers</h4>
        <input type="text"
          value={text} 
          onInput={(e) => this.setState({ text: e.target.value })} />
        <button onClick={() => this.props.onSubmit(this.state.text)}>Send to the parent</button>
      </div>
    )
  }
}

一些新手的问题:

1我在哪里调用索引,以便设置状态附加到状态。回答正确问题id并将答案id增加1? 2我应该把嵌套答案作为问题的属性吗? 谢谢你的帮助!

展开
收起
sossssss 2019-12-09 17:04:10 976 0
0 条回答
写回答
取消 提交回答
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
用计算和数据去改变整个世界 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载