constructor(props) {
super(props);
this.submitQA = this.submitQA.bind(this);
this.onSearchChange = this.onSearchChange.bind(this);
this.isSearched = this.isSearched.bind(this);
this.answerSubmitted = this.answerSubmitted.bind(this);
this.reset = this.reset.bind(this);
this.state = {
answers: [],
answer: '',
searchTerm: '',
}
}
reset() {
console.log("reset");
}
render() {
const answer = true;
return (
<div className="App">
<div className="center">
<form >
Search: <input type="text" onChange={this.onSearchChange} /><br/>
</form>
<form onSubmit={this.submitQA}>
Q & A:
<input type="text" placeholder=" Course/Q/A"/>
<button type="submit"> Submit </button>
</form>
<span>{basicFormat}</span>
</div>
{
this.state.answers.filter(this.isSearched(this.state.searchTerm)).map((item) => {
return (
if(answer) {
this.reset;
}
<div>
<form onSubmit={this.answerSubmitted}>
<text> {item} </text>
<input type="text" placeholder="answer the question"/>
</form>
</div>
)
})
}
</div>
);
}
为什么我不能在这个渲染方法中使用任何逻辑?继续给我意想不到的令牌。看不出有任何问题。看了一些教程,他们正在做同样的事情,但为什么我的错误呢?
答案 0 :(得分:1)
你在回复中包含了一个Javascript if
语句,与JSX混合在一起。
Quoting the React documentation:
if
语句和for
循环不是JavaScript中的表达式,因此它们不能直接在JSX中使用。相反,您可以将它们放在周围的代码中。
要修复意外的令牌错误,请在if
之前移动return
语句:
{
this.state.answers.filter(this.isSearched(this.state.searchTerm)).map((item) => {
if(answer) {
this.reset();
}
return (
<div>
<form onSubmit={this.answerSubmitted}>
<text> {item} </text>
<input type="text" placeholder="answer the question"/>
</form>
</div>
)
})
}
我还建议您在render
函数返回之前执行映射。这样,渲染就可以更清楚地与数据操作分离。
render() {
const answer = true;
const answerForms = this.state.answers
.filter(this.isSearched(this.state.searchTerm))
.map((item) => {
if (answer) {
this.reset()
}
return (
<div>
<form onSubmit={this.answerSubmitted}>
<text> {item} </text>
<input type="text" placeholder="answer the question" />
</form>
</div>
)
})
return (
<div className="App">
<div className="center">
<form >
Search: <input type="text" onChange={this.onSearchChange} /><br />
</form>
<form onSubmit={this.submitQA}>
Q & A:
<input type="text" placeholder=" Course/Q/A" />
<button type="submit"> Submit </button>
</form>
<span>{basicFormat}</span>
</div>
{answerForms}
</div>
)
}