【问题标题】:If inside fat arrow function如果在胖箭头函数内
【发布时间】:2018-02-01 03:08:43
【问题描述】:

我不知道怎么写。我在胖箭头中有这个三元运算符。但如果无法执行代码。我在 browserify 或控制台上没有收到任何错误,但它只是不打印标题。

如果我删除 {} 和三元运算符,它可以正常工作。

我写错了什么?

<Row className="grid-header">
    {
        this.props.columnsInfo.map((info) => {
            width = (info.colWidth) ? "className={info.colWidth}" : "xs={this.calculateColumnSize()}";
            <Col style={{ paddingTop: 10, paddingLeft: 10 }} key={info.header} width>{info.header}</Col>
        })
    }
</Row>

【问题讨论】:

    标签: javascript arrays if-statement jsx higher-order-functions


    【解决方案1】:

    你只是忘记了map()中的return
    map() 中,每次迭代都会返回undefined,这将被忽略,因为没有要渲染的想法。
    当您使用 fat arrow function with "{}" 时,您必须显式返回 ((x) =&gt; {return x + x}) 一个变量,但 没有 有一个隐式返回 ((x) =&gt; x + x) .

    解决方案

    <Row className="grid-header">
        {
            this.props.columnsInfo.map(info => {
                const width = info.colWidth 
                  ? "className={info.colWidth}"
                  : "xs={this.calculateColumnSize()}";
                return <Col style={{ paddingTop: 10, paddingLeft: 10 }} key={info.header} width>{info.header}</Col>
            })
        }
    </Row>
    

    【讨论】:

    • @dfsq 我把它改成const width。当我回答主要错误时没有注意到它。谢谢..
    【解决方案2】:

    如果不是胖箭头函数的整个主体,则需要显式返回 jsx。

    您的代码已修复:

    <Row className="grid-header">
        {this.props.columnsInfo.map(info => {
                const width = (info.colWidth)? "className={info.colWidth}" : "xs={this.calculateColumnSize()}";
                return (<Col style={{paddingTop:10,paddingLeft:10}} key={info.header} width>{info.header}</Col>);
        })}
    </Row>
    

    删除花括号和三元运算符时它起作用的原因是,当您为主体执行没有花括号的胖箭头函数时,它会隐式返回主体,该主体必须只有一个语句。由于您在函数体中添加第二条语句(三元行),因此您需要添加体大括号,现在有体大括号,您需要实际编写 return 关键字,因为它不再隐含你的 jsx 线。

    【讨论】:

    • 很好的解释 TW80000。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多