Javascript 对象作为子文本输入无效
以下是我认为给我带来麻烦的代码:Javascript 对象作为子文本输入无效,javascript,reactjs,Javascript,Reactjs,以下是我认为给我带来麻烦的代码: class App extends Component { constructor(props) { super(props); this.state = { key: uuid(), title: "", author: "", questions: [], answers: [] }; this.handleChange = this.handleChange.
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>
我今天真的没有太多了。如果你有问题,请告诉我(这样做是因为我显然需要更多的话),任何帮助都是感激的,谢谢 在
addQuestion
函数(您在componentDidMount
中调用该函数)中,您正在将对象推送到答案
,但渲染方法希望它是一个组件。更改答案。按
可按组件而不是对象
也许像这样:
answers.push(<input
type="text"
onChange={this.handleChange}
name={uuid()}
/>);
answers.push();
请注意,我将您的输入重命名为
uuid
。这可能不可取,但必须是唯一的。您可以包括您的整个渲染方法吗?您可以发布完整的组件吗。奇怪的是,为什么名字必须是唯一的?它们是否以某种方式使用?因为在setState
函数中,您使用[name]
作为状态值的键。如果这不是唯一的,那么您将覆盖您的状态。哦,让sa更有意义。顺便说一句,这成功了,谢谢!
answers.push(<input
type="text"
onChange={this.handleChange}
name={uuid()}
/>);