这是我认为给我带来麻烦的代码:
class App extends Component {
constructor(props) {
super(props);
this.state = {
key: uuid(),
title: "",
author: "",
questions: [],
answers: []
};
this.handleChange = this.handleChange.bind(this);
this.addQuestion = this.addQuestion.bind(this);
this.removeItem = this.removeItem.bind(this)
}
componentDidMount() {
// componentDidMount() is a React lifecycle method
this.addQuestion();
}
handleChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
removeItem (index) {
this.setState(({ questions }) => {
const mQuestions = [ ...questions ]
mQuestions.splice(index, 1)
return { questions: mQuestions }
})
}
addQuestion() {
questionNum++;
this.setState(previousState => {
const questions = [
...previousState.questions,
<input
type="text"
onChange={this.handleChange}
name="question"
key={uuid()}
/>,
"hi"
];
const answers = [
...previousState.answers,
<input
type="text"
onChange={this.handleChange}
name="answer"
/>,
];
for (var i = 0; i < 4; i++) {
answers.push({
answerChoice: "",
key: uuid()
});
}
return { questions, answers };
});
console.log(
this.state.answers,
this.state.questions,
questionNum,
this.state.title,
this.state.author
);
}
//yada yada
<div className="questions">
Now let's add some questions... <br />
{// This is where we loop through our questions to
// add them to the DOM.
this.state.questions.map(question => {
return (
<div>
{question}
{
this.state.answers.map(answer => {
return (
<div>
{answer}
</div>
);
})
}
</div>
我无法获取我的 answerChoice~ inputs or
答案inputs to show up in the DOM. The arrays are there when i do
console/log()` 但不是 DOM 中的实际输入。我对 React 和 Javacript 很陌生,所以我真的不知道我在做什么。我现在收到此错误:
AnswerChoice, key}). If you meant to render a collection of children, use an array instead.
in div (at App.js:136)
in div (at App.js:131)
in div (at App.js:125)
in form (at App.js:105)
in div (at App.js:104)
in div (at App.js:93)
in App (at index.js:7)
今天我真的没有太多事情了。如果您有疑问,请告诉我(这样做是因为我显然需要更多文字)任何帮助都是感激的,谢谢!
最佳答案
在您的 addQuestion
函数(您在 componentDidMount
中调用)中,您正在将一个对象推送到 answers
,但您的渲染方法需要它成为一个组件。更改 answers.push
以推送组件而不是对象。
也许像这样:
answers.push(<input
type="text"
onChange={this.handleChange}
name={uuid()}
/>);
请注意,我将您的输入重命名为 uuid
。这可能并不理想,但必须是唯一的。
关于javascript - 对象作为 React 子对象无效 - 文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51290908/