Reactjs 反应-根据条件显示地图中的第一项

Reactjs 反应-根据条件显示地图中的第一项,reactjs,Reactjs,我有 一个简单的问题是,是否可以根据条件显示地图中的第一项 因此,在我的示例中,如果“first”为true,我如何输出第一项“1” import React, { Component } from "react"; import { render } from "react-dom"; import "./style.css"; const App = () => { const list = ["1"

我有

一个简单的问题是,是否可以根据条件显示地图中的第一项

因此,在我的示例中,如果“first”为true,我如何输出第一项“1”

import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

const App = () => {
  const list = ["1", "2", "3", "4"];

  const first = true

  return (
    <div>
      <ul>
        {list.map(item => (
          <li>{item}</li>
        ))}
      </ul>
    </div>
  );
};

render(<App />, document.getElementById("root")); 
import React,{Component}来自“React”;
从“react dom”导入{render};
导入“/style.css”;
常量应用=()=>{
常数列表=[“1”、“2”、“3”、“4”];
const first=true
返回(
    {list.map(项=>(
  • {item}
  • ))}
); }; render(,document.getElementById(“根”));

{list.map((项目,i)=>{
如果(i==0&&item)返回
  • {item}
  • ; })}
    {list.map((项目,索引)=>(
    
  • {first?(索引===0?项:空):项}
  • ))}
      { list.map((项目、索引)=>( (索引===0&&first)?
    • {item}
    • :null )) }

    试试上面的代码。

    这应该可以。如果
    first
    为true,则仅显示第一个元素,否则将显示所有元素

    const App = () => {
      const list = ["1", "2", "3", "4"];
    
      const first = false;
    
      return (
        <div>
          <ul>
            {first ? (
              <li>{list[0]}</li>
            ) : (
              list.map((item, index) => {
                return <li>{item}</li>;
              })
            )}
          </ul>
        </div>
      );
    };
    
    const-App=()=>{
    常数列表=[“1”、“2”、“3”、“4”];
    const first=false;
    返回(
    
      {首先(
    • {list[0]}
    • ) : ( list.map((项目、索引)=>{ 返回
    • {item}
    • ; }) )}
    ); };
    这不会显示未编制索引的项目0这不是问题的答案,这就是我指出的原因?如果第一个id为true或false,这会输出所有项目如果“first”为true或false,则只输出第一个项目,我需要基于条件的第一项我刚刚更新了答案这是结束,但我想显示第一项,这将隐藏它-@lomine更新了答案。希望这就是你想要的工作方式。
    {list.map((item, index) => (
              <li>{first ? (index === 0 ? item : null) : item}</li>
     ))}
    
    <ul>
        {
            list.map((item,index) => (
                (index === 0 && first) ? <li>{item}</li> : null
            ))
        }
    </ul>
    
    const App = () => {
      const list = ["1", "2", "3", "4"];
    
      const first = false;
    
      return (
        <div>
          <ul>
            {first ? (
              <li>{list[0]}</li>
            ) : (
              list.map((item, index) => {
                return <li>{item}</li>;
              })
            )}
          </ul>
        </div>
      );
    };