简体   繁体   English

如果里面有胖箭头功能

[英]If inside fat arrow function

Im not sure how to write this. 我不知道该怎么写。 I have this ternary operator inside the fat arrow. 我在粗箭头里面有这个三元运算符。 but if fails to execute the code. 但是如果执行代码失败。 I get no errors with browserify or on console, but it just does not print the headers. 我没有在browserify或控制台上出现任何错误,但是它只是不打印标题。

If I drop the {} and ternary operator it works fine. 如果我放弃{}和三元运算符,它将正常工作。

What am I typing wrong? 我打错了什么?

<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>

You just forgot the return inside map() . 您只是忘记了map()内的返回值
Inside map() you return for each iteration undefined and this will be ignored because there is nothink to render. map()内部,您将为每个undefined迭代返回,这将被忽略,因为没有提示。
When you use your fat arrow function with "{}" you have to explicit return ( (x) => {return x + x} ) a variable but without there is a implicitly return ( (x) => x + x ). 当将fat arrow function “ {}”一起使用时,必须显式返回( (x) => {return x + x} )变量,但没有隐式返回( (x) => x + x )。

Solution

<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>

You need to explicitly return the jsx if it's not the entire body of the fat arrow function. 如果不是胖箭头函数的整个主体,则需要显式返回jsx。

Your code fixed: 您的代码已修复:

<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>

The reason it works when you remove the curly braces and ternary operator is because when you do a fat arrow function without curly braces for the body, it implicitly returns the body, which must be only one statement. 删除大括号和三元运算符时起作用的原因是,当您执行不带大括号的胖箭头功能时,它隐式地返回了主体,该主体只能是一条语句。 Since you're adding a second statement in the function body (the ternary line), you need to add the body braces, and now there there are body braces, you need to actually write the return keyword because it's no longer implicit for your jsx line. 由于您要在函数主体(三元行)中添加第二条语句,因此需要添加主体括号,而现在有了主体括号,您需要实际编写return关键字,因为它不再对jsx隐含线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM