reactjs - 在 React 中显示逗号分隔的数组元素

标签 reactjs jsx

 class App extends Component {
    constructor(props){
    super(props);
    this.state={ recipes :[] } 
    this.addRecipe=this.addRecipe.bind(this);
    }

    addRecipe (recipe) {
    console.log({...recipe})
      this.setState({ 
      recipes: [...this.state.recipes, recipe]
    });
    }
    componentWillMount(){
    this.setState({
      recipes : require('./sample-recipes')
    });
    } 
    render() {
    return (
      <div className="App">
      <h2>Welcome to the Recipe Book</h2>
      <dl>
      {this.state.recipes.map(recipe => {
        return ( <div key={recipe.name}>
                 <dt>{recipe.name}</dt>
                 <dd>{recipe.ingredient}</dd>
                 <hr></hr>
                 </div>
                 )
      })
     }
      </dl>
     <button className="addButton" onClick={() => 
      {this.setState({ display: !this.state.display })}}>
     Add Recipe
     </button>
     <AddRecipe addRecipe={this.addRecipe} 
     display={this.state.display} />
     </div>
     );
     }

}

我的sample-recipe.js文件如下
module.exports = [ 
{
name : 'chicken',
ingredient : ['spinach','chillies']
  }];    

嗨,我是 React 的新手。我正在制作这个食谱书项目。
我想显示以空格或逗号分隔的成分。
现在它显示为“菠菜”。
这是使成分成为数组的正确方法吗?

最佳答案

由于成分是 array of strings您可以join它创建一个字符串并显示结果

{this.state.recipes.map(recipe => {
        return ( <div key={recipe.name}>
                 <dt>{recipe.name}</dt>
                 <dd>{recipe.ingredient.join(",")}</dd>
                 <hr></hr>
                 </div>
                 )
      })
     }

关于reactjs - 在 React 中显示逗号分隔的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43309773/

相关文章:

javascript - React Marquee 模块给出错误

javascript - 在不同的媒体查询中预览 react 组件

javascript - 在 REACTJS 中的函数中显示渲染结果

node.js - 在 react 中从数据库获取数据的正确方法是什么?

javascript - JSX 条件渲染语法错误

reactjs - Heroku : puppeteer chrome: error while loading shared libraries: libX11-xcb. so.1

javascript - JSX 脚本在 Photoshop 中输出多个不同名称的图像

javascript - 如何在 JavaScript 中编写 import 语句而不是 require 语句?

javascript - 如何在 React 中使用 leader-line(一个外部 javascript 库)?

javascript - 使用 Helmet 嵌入第三方聊天小部件