首页 > 解决方案 > 有条件地渲染材质复选框

问题描述

我在我的 React 应用程序中使用 Material UI,它采用 JSON 数据来显示文本和其他数据。

{ "included": [{ "name": "someName", "price": "0", "required": true }] }

我创建了这个变量:它在控制台日志 const isRequired = useState(Included[0].required); 中返回。true

此 JSON 对象中的所有其他数据在我的Map函数中呈现良好,但现在我想使用required布尔值有条件地呈现复选框。

{Included.map((include) => {
    console.log('includes', include);
    return (
      <div className="serviceWrapper" key={include.id}>
        <FormControlLabel
          value="end"
          control={
            !isRequired ? (
              <Checkbox
                color="primary"
                onChange={() => {
                  setSomeData(!someData);
                }}
              />
            ) : null
          }
          label={i18next.t('BOX.info')}
          labelPlacement="End"
        />
        <span className="price_right">
          {include.price > 0 ? include.price : ''}
        </span>
      </div>
    );
  })}

Unhandled Rejection (TypeError): Cannot read property 'props' of null但是,这会在 index.js 中返回错误。我不确定我是否可以按照我尝试的方式操作 Material UI Checkbox。还有其他方法可以做到这一点吗?

标签: javascriptreactjsmaterial-ui

解决方案


根据文档, 的control属性FormControlLabel必需的。(如果您将鼠标悬停在*它旁边,工具提示会显示“必需”。)为其提供null服务将不起作用。看来你必须把整个FormControlLabel关掉。


推荐阅读