React Typescript:将字符串数组呈现为无序列表

时间:2019-10-02 07:05:10

标签: reactjs typescript

在使用打字稿的纯功能组件中,我们如何将字符串数组呈现为无序列表?

import React from 'react';

const Drinks: React.FC = () => {
   const myArray = ['Water', 'Orange Juice', 'Milk'];

  return (    
    <ul>
     <li>Water<li/>
     <li>Orange Juice<li/>
     <li>Milk<li/>
    </ul>
  );
}

export { Drinks };

4 个答案:

答案 0 :(得分:0)

您可以将map用作子代:

const Drinks: React.FC = () => {
  const myArray = ['Water', 'Orange Juice', 'Milk'];

  return (    
    <ul>
     {myArray.map(o => <li key={o}>{o}</li>)}
    </ul>
  );
}

export { Drinks };

play

注意 key = {o}对于帮助唯一地标识要更新的元素有必要。假设字符串在数组中是唯一的。

答案 1 :(得分:0)

import React from 'react';

const Drinks: React.FC = () => {
   const myArray = ['Water', 'Orange Juice', 'Milk'];

  return (    
    <ul>
     {myArray.map((item:string, index:number)=><li key={index}>{item}</li>)} 
     /* using index number as key is not recommendable. 
        But in this case, it doesn't matter.*/ 
    </ul>
  );
}

export { Drinks };

答案 2 :(得分:-1)

<div class="solid">

  <div class="input-group">
    <input type="text" ng-model="c.data.message" class="form-control" aria-label="...">
    <div class="input-group-btn">
      <button type="submit" ng-click="c.add()" class="btn btn-primary">Search</button>
    </div>
  </div>

</div>

答案 3 :(得分:-1)

您可以使用map渲染数组,例如

<ul> 
    {myArray.map((arr,i) => 
     return <li key={i}>{arr}</li>
    ) 
</ul>
  • 如果直接myArray无法访问,请尝试this.myArray