Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

javascript - can i write a function or just create a variable inside jsx element?

What my aim is to create a variable to store a result of if condition, which will be used to render html things.

<TableBody>
  {() => { //---> Not Getting into this function
    const source =                              
      selectedPerformance.length > 0
      ? selectedPerformance
      : performance;
    source.map((emp) => {
      const isItemSelected = isSelected(emp.id);
      return (
        <TableRow hover key={emp._id}>
          <TableCell>{emp.id}</TableCell>
        </TableRow>
      )
    }
</TableBody>

But when I try this I didn't get type errors. I thought it will work but it was not getting into the function.

I know that I can write it in different way, like without creating that function and variable inside the jsx just by using conditional rendering, but for that i have to repeat the same code again and again. I don't want to do that.

Is there any better way?

question from:https://stackoverflow.com/questions/65873823/can-i-write-a-function-or-just-create-a-variable-inside-jsx-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your fat arrow functions as whereas your map function seem to luck matching closing '}' and ')' respectively.

After fixing that, you could make your outmost fat arrow to become an IIFE(Immediately Invoked Function Expression).

(function () {
    statements
})();    

https://developer.mozilla.org/en-US/docs/Glossary/IIFE

<TableBody>
    {
        (() => {
            const source =
                selectedPerformance.length > 0
                    ? selectedPerformance
                    : performance;
            source.map(
                (emp) => {
                    const isItemSelected = isSelected(emp.id);
                    return (
                        <TableRow hover key={emp._id}>
                            <TableCell> {emp.id} </TableCell>
                        </TableRow>
                    )
                }
            )

        })()
    }
</TableBody>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...