简体   繁体   English

如何添加一个条件来反应 material-ui 个元素?

[英]How do I add a condition to react material-ui elements?

I am building a generic data.table using react and material-ui. My background is c# and java, and early javascript, so I'm having issues w/the syntax in reactjs.我正在使用 React 和 material-ui 构建一个通用的 data.table。我的背景是 c# 和 java,以及早期的 javascript,所以我在 reactjs 中遇到语法问题。

Specifically I have the following code:具体来说,我有以下代码:

  <TableRow>
    {formColumns.map((x, i) =>
      ---WRAP THE FOLLOWING IN A CONDITION
      <TableHeaderColumn key={`thc-${i}`}>
        <div
          style={{
            display: "flex",
            alignItems: "center"
          }}
          onClick={() => handleSort(x.name)}
        >
          <span>{x.label}</span>
          {columnToSort === x.name ? (
            sortDirection === "asc" ? (
              <ArrowDownwardIcon fontSize='small' />
            ) : (
                <ArrowUpwardIcon fontSize='small' />
              )
          ) : null}
        </div>
      </TableHeaderColumn>
      ---WRAP THE ABOVE IN A CONDITION
    )}
    <TableHeaderColumn>
      <CheckboxMenu formColumns={formColumns} />
    </TableHeaderColumn>
  </TableRow>

The object I'm using for the 'map' is defined as follows:我用于“地图”的 object 定义如下:

{    id: {
      name: 'id',
      displayColumn: false,
      displayOrder: 1,
    },
    firstName: {
      name: 'firstName',
      label: 'First name*',
      requiredErrorMsg: 'First name is required',
      displayColumn: true,
      displayOrder: 2,
    },
 ...
}

I want to wrap the above elements in a condition that looks like this:我想将上述元素包装在如下所示的条件中:

if (x.displayColumn === true)
{
  ---PUT THE ABOVE CODE BETWEEN THE WRAP COMMENTS HERE
}
else
{
  do nothing
}

Seems like an easy thing to do right?看起来很容易做对吧? It is in any other language I've used.它是我用过的任何其他语言。 But reactjs keeps giving me syntax errors.但是 reactjs 一直给我语法错误。 Can someone put the above code together correctly and explain to me what I'm doing wrong?有人可以将上面的代码正确地放在一起并向我解释我做错了什么吗? I can't find an answer to this issue anywhere.我无法在任何地方找到这个问题的答案。 Help is much appreciated!非常感谢您的帮助!

EDITED TO ADD THE FOLLOWING:编辑添加以下内容:

When I attempt to do this:当我尝试这样做时:

  <TableRow>
    {formColumns.map((x, i) =>
    {
      x.displayColumn === true ? (

        <TableHeaderColumn key={`thc-${i}`}>
          <div
            style={{
              display: "flex",
              alignItems: "center"
            }}
            onClick={() => handleSort(x.prop)}
          >
            <span>{x.label}</span>
            {columnToSort === x.name ? (
              sortDirection === "asc" ? (
                <ArrowDownwardIcon fontSize='small' />
              ) : (
                  <ArrowUpwardIcon fontSize='small' />
                )
            ) : null}
          </div>
        </TableHeaderColumn>
      ) : (null) <--ERROR
    }
    )}
    <TableHeaderColumn>
      <CheckboxMenu formColumns={formColumns} />
    </TableHeaderColumn>
  </TableRow>

I get this error:我收到此错误:

"(ESLint) Expected an assignment or function call and instead saw an expression." “(ESLint)期待一个赋值或 function 调用,而是看到一个表达式。”

Before someone mentions the (null), I've tried (''), ("") and anything else.在有人提到 (null) 之前,我已经尝试过 ('')、("") 和其他任何方法。 I still get the same error.我仍然遇到同样的错误。 The fact is I'd rather use an if statement, since there IS NO ELSE.事实上,我宁愿使用 if 语句,因为没有其他语句。

You were missing the return statement你错过了return声明

<TableRow>
  {formColumns.map((x, i) => {
    // return statement here
    return (
      x.displayColumn === true && (
        <TableHeaderColumn key={`thc-${i}`}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
            }}
            onClick={() => handleSort(x.prop)}
          >
            <span>{x.label}</span>
            {columnToSort === x.name ? (
              sortDirection === "asc" ? (
                <ArrowDownwardIcon fontSize="small" />
              ) : (
                <ArrowUpwardIcon fontSize="small" />
              )
            ) : null}
          </div>
        </TableHeaderColumn>
      )
    );
  })}
  <TableHeaderColumn>
    <CheckboxMenu formColumns={formColumns} />
  </TableHeaderColumn>
</TableRow>;

The syntax is as follows语法如下

<TableRow>
  {formColumns.map((x, i) => {
    return <div>Something</div>
  })}
</TableRow>

OR或者

{formColumns.map((x, i) => (
    <div>Something</div>
))}

Because () => { return smthg; }因为() => { return smthg; } () => { return smthg; } is equivalent to () => (smthg) or () => smthg and you have to return something from the .map callback to get your JSX evaluated. () => { return smthg; }等效于() => (smthg)() => smthg ,您必须从.map回调中返回一些内容才能评估您的 JSX。

Btw.顺便提一句。 conditional statement in React is just && due to JS specifics.由于 JS 的特殊性,React 中的条件语句只是&&

Because, in the code flag && someFunc() someFunc never gets called if flag is false.因为,在代码flag && someFunc()中,如果flag为假,则永远不会调用 someFunc。 Therefore, doing this way your JSX would never get evaluated and never rendered.因此,这样做你的 JSX 永远不会被评估和渲染。

You can use ternary operator to decide the condition.您可以使用三元运算符来决定条件。

EX:前任:

<TableRow>
  {formColumns.map((x, i) => (
    x.displayColumn
      ? (
        // PUT THE ABOVE CODE BETWEEN THE WRAP COMMENTS HERE
      )
      : null
    )
  )}
  <TableHeaderColumn>
    <CheckboxMenu formColumns={formColumns} />
  </TableHeaderColumn>
</TableRow>

If anyone is still looking for another solution, on Material UI 4 this works for me如果有人仍在寻找其他解决方案,那么在 Material UI 4 上这对我有用

const [activeElement, setactiveElement] = useState(false);


const classes = useStyles({activeElement});//Sent as object

return (
<div onMouseEnter={() => setHoverActive(true)} onMouseLeave={() => setHoverActive(false)} className={classes.card}>

</div>
);

/* Outside the export element */

const useStyles = makeStyles((theme) => ({
    card: {
        backgroundColor: ({activeElement}) => activeElement ? "red": "blue",    
    }

})

In this case, when you hover, the background color change... This base on conditions of true/false.在这种情况下,当您输入 hover 时,背景颜色会发生变化……这取决于真/假条件。 A simple example for conditions in Material UI, hope this is use full for someone Material UI 中条件的一个简单示例,希望这对某些人有用

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

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