Reactでkeyを使ったレンダリングを試したかったのですが、配列の要素の値(文字列)ではなく、数字が出力されてしまいます。要素の値を出力するにはでのように直せばいいのでしょうか。
環境は
Sandbox Editor
を使用しています。
ソースコード
Javascript
1//index.js 2import React from "react"; 3import ReactDOM from "react-dom"; 4 5import KeyTest from "./hello"; 6 7import "./styles.css"; 8 9const animals = ["cat", "dog", "rabbit"]; 10 11function App() { 12 return <KeyTest data={animals} />; 13} 14 15const rootElement = document.getElementById("root"); 16ReactDOM.render(<App />, rootElement);
javascript
1// hello.js 2import React, { Component } from "react"; 3 4const KeyTest = (props) => { 5 return ( 6 <ul> 7 // 配列データに対して、mapメソッドを使って値を組み込んだJSXを返す 8 {props.data.map((index, text) =>{ 9 // key={} でループのインデックスを指定する 10 return <li key={index}> {text} </li>; 11 })} 12 </ul> 13 14 ); 15}; 16 17export default KeyTest;
html
1<!-- index.html --> 2<!DOCTYPE html> 3<html lang="en"> 4 5<head> 6 <meta charset="utf-8"> 7 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 8 <meta name="theme-color" content="#000000"> 9 10 <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> 11 <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 12 13 <title>React App</title> 14</head> 15 16<body> 17 <noscript> 18 You need to enable JavaScript to run this app. 19 </noscript> 20 <div id="root"></div> 21 22</body> 23 24</html>
実行結果
・0 ・1 ・2
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/18 12:51