如何在ReactJS中的渲染方法中添加条件

时间:2019-08-16 16:45:50

标签: reactjs react-redux

我正在使用以下组件创建下拉列表。但是,如果下拉列表中有一个值且d.datasetid等于0,则该值不应出现在下拉列表中,这意味着下拉列表中应填充空白,还需要显示一条错误消息,指出该值不存在。请帮助我,因为我是ReactJS的新手。

import React from 'react'
import {Form, Col, FormGroup, ControlLabel, DropdownButton, MenuItem, ButtonGroup} from 'react-bootstrap'

const getId = (obj) => obj.datasetid + ''

export const DatasetSelector = ({label, dataArr, selected, onChange}) => {
  const onChangeHandler = (key) => {
    onChange(key)
  }
  let title = 'Select a Dataset'
  if (selected && dataArr.length > 0) {
    const ds = dataArr.filter((d) => getId(d) === selected)
    if (ds[0]) {
      title = ds[0].datasetname
    }
  }

  return (
    <Form horizontal>
      <FormGroup controlId='dsSelector'>
        <Col componentClass={ControlLabel} xs={12} sm={4} md={4}>{label}</Col>
        <Col xs={12} sm={8} md={8}>
          <ButtonGroup vertical={false}>
            <DropdownButton id='DatasetSelect' bsSize='small' title={title} onSelect={onChangeHandler}>
              {dataArr.map(d =>
                <MenuItem key={getId(d)} active={getId(d) === selected} eventKey={getId(d)}>
                  <b>{d.datasetname}</b> - <small>{d.datasetdescription}</small>
                </MenuItem>
              )}
            </DropdownButton>
          </ButtonGroup>
        </Col>
      </FormGroup>
    </Form>
  )
}

1 个答案:

答案 0 :(得分:2)

您可以这样做:

{dataArr.length === 1 && dataArr[0].datasetid === 0 ? '' : dataArr.map(d =>
    <MenuItem key={getId(d)} active={getId(d) === selected} eventKey={getId(d)}>
         <b>{d.datasetname}</b> - <small>{d.datasetdescription}</small>
     </MenuItem>
)}

或者您可以这样做:

const MenuItems = ((empty) => {
    if (empty) return '';
    return dataArr.map(d =>
        <MenuItem key={getId(d)} active={getId(d) === selected} eventKey={getId(d)}>
            <b>{d.datasetname}</b> - <small>{d.datasetdescription}</small>
        </MenuItem>
    )}
})(dataArr.length === 1 && dataArr[0].datasetid === 0);

// ...

return (
    // ...
    <DropdownButton id='DatasetSelect' bsSize='small' title={title} onSelect={onChangeHandler}>
        {MenuItems}
    </DropdownButton>
    // ...
)