【问题标题】:'}' Expected in React Component Render Method (Using JSX)'}' 预期在 React 组件渲染方法中(使用 JSX)
【发布时间】:2021-01-11 16:55:42
【问题描述】:

在下面给出的代码中调用函数表达式之前,我收到一条错误消息“期待 '}''。

class IfElse extends React.Component{
    render(){
        return(
            <div>
                {
                    (booleanExp)=>{
                        return(
                        <a href={(booleanExp)?'login':'logout'}>{(booleanExp)?'login':'logout'}</a>
                        )
                    }(this.props.booleanExp)
                }
            </div>
            
        )
    }
};

错误在这里:}(this.props.booleanExp),就在大括号之后。如果我删除函数调用,则没有错误但是我需要函数调用。

【问题讨论】:

  • 添加这个圆括号有什么意义?
  • 我想你问的是return之后的那些。它们只是为了避免任何意外的语法错误。

标签: reactjs jsx


【解决方案1】:

将函数包装在()中。

例如:

((booleanExp)=>{
    return(
        <a href={(booleanExp)?'login':'logout'}>{(booleanExp)?'login':'logout'}</a>
    )
})(this.props.booleanExp)

【讨论】:

  • 是的,有效!我真的很感谢你的贡献。如果您愿意,我会要求您解释问题以及括号解决问题的原因,否则您将获得支持。
  • 请参考this
【解决方案2】:
class IfElse extends React.Component {
  render() {
    return (
      <div>
        {
          (booleanExp) => (
            <a href={(booleanExp) ? 'login' : 'logout'}>{(booleanExp) ? 'login' : 'logout'}</a>
          )(this.props.booleanExp)
        }
      </div>

    )
  }
};

【讨论】:

  • 不!它不起作用。它只是简单的 JavaScript 内联未定义类型的函数,我确信只有花括号用于正文。
【解决方案3】:

为什么需要在 render 方法中调用函数?你能简单地使用三元表达式吗:

class IfElse extends React.Component{
    render(){
        return(
            <div>
                <a href={this.props.booleanExp ? 'login' : 'logout'}> 
                  {this.props.booleanExp ? 'login' : 'logout'}
                </a>
            </div>
            
        )
    }
};

甚至将其简化为功能组件:

const IfElse = ({booleanExp}) => (
 <div>
   <a href={booleanExp ? 'login' : 'logout'}> 
     {booleanExp ? 'login' : 'logout'}
   </a>
 </div>
);

【讨论】:

  • 非常感谢您的贡献,但正如我所说,函数调用对我来说是必需的。我只是在学习 React,这就是原因。
猜你喜欢
  • 2019-05-17
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 2015-05-16
  • 2018-10-01
相关资源
最近更新 更多