在JSX中立即调用函数表达式 [英] Immediately-invoked function expression inside JSX
问题描述
我正在研究我正在尝试编译的React项目,但无法找到我收到此语法错误的原因。具体来说,模式{()=> {}()}在这种情况下是做什么的?
I am working on the React project where I am trying to compile but cannot find why I am getting this syntax error. Specifically, what the pattern, "{()=>{}()}", is doing in this context?
Module build failed: SyntaxError: Unexpected token, expected } (35:9)
33 | return (<div className="loading" />);
34 | }
35 | }()}
| ^
36 | </div>
37 | );
38 | }
@ ./src/containers/SearchApp.js 7:0-52
@ ./src/containers/App.js
@ ./src/index.js
@ multi ./src/index
代码的一部分:
The part of code:
render() {
return (
<div>
<div className="form-group">
<input onKeyDown={this.searchEnter.bind(this)} type="text" ref="tag" className="form-control input-lg search-bar" placeholder="Enter the tag..." />
<button onClick={this.searchClick.bind(this)} type="button" className="btn btn-default search-button">Search!</button>
</div>
{()=>{
if (this.props.status === 'PENDING') {
return (<div className="loading" />);
}
}()}
</div>
);
推荐答案
这是立即调用的函数表达式。
您的代码出错?
Error With your code?
您需要将函数包装在()中,请检查:
You need to wrap the function inside (), Check this:
{
(() => {
if (this.props.status === 'PENDING') {
return (<div className="loading" />);
}
})()
}
模式{()=> {}()}在这种情况下是做什么的?
what the pattern, "{()=>{}()}", is doing in this context?
直接我们不能将if / else语句或任何其他语句放在JSX中,所以我们需要创建一个函数并将所有逻辑放在其中。
Directly we can't put if/else statement or any other statement inside JSX, so for that we need to create a function and put all the logic inside that.
根据 DOC :
As per DOC:
if-else语句在JSX中不起作用。这是因为JSX只是函数调用和对象构造的
语法糖。如果三元表达式不够健壮,您可以在JSX之外使用if语句来确定应该使用哪些组件。或者如果您更喜欢更内联的美学,请在JSX中定义立即调用的函数表达式。
编写相同代码的另一种方式:
render(){
return(
<div>
<div className="form-group">
....
</div>
{this._callFun()}
</div>
)
}
_callFun(){
if (this.props.status === 'PENDING') {
return (<div className="loading" />);
}
}
这篇关于在JSX中立即调用函数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!