我有两个数据对象和三个分层组件,或者在沙箱中这里。数据包含一个问题列表,每个问题的下方都有一个输入框,允许多个回答。然而,我不知道如何在输入对特定问题的回答后正确更新正确问题的状态。 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我应该把嵌套答案作为问题的属性吗? 谢谢你的帮助!
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。