如果在胖箭头函数内

If inside fat arrow function

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

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

我打错了什么?

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

你只是忘记了 return 里面 map().
map() 中你 return 每次迭代 undefined 并且这将被忽略,因为没有考虑渲染。
当您使用 fat arrow function with "{}" 时,您必须显式 return ((x) => {return x + x}) 变量但 without 有一个隐含的 return ((x) => 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>

如果 jsx 不是胖箭头函数的整个主体,则需要明确 return 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 是主体,它必须只有一个陈述。由于您要在函数体(三元行)中添加第二条语句,因此需要添加函数体大括号,现在有了函数体大括号,您需要实际编写 return 关键字,因为它不再隐含在您的 jsx 行中。