- Objective: - Breadcrumb: # 概念阐释 # 实例 # 相关内容 # 问题 - [[js objects forin loop 遍历获取对象属性]] - for...in loop 与 forEach的区别? - [[JSX 事件处理程序]] - 为什么e.target.alt可以获取到img中的alt值? - 想要获得对象索引或random索引,结尾永远是? - [[JSX condition 逻辑操作符]] - [[JSX condition if]] - 两者的区别? - 赋空值和不赋值的区别? # 问题答案 ```jsx import { animals } from './animals'; import React from 'react'; import {createRoot} from 'react-dom/client'; const container = document.getElementById('app'); const root = createRoot(container); const title = ''; const background = <img class="background" alt="ocean" src='/images/ocean.jpg'/> const showBackground = false;//决定是否出现背景 // 定义images数组,用for...in loop循环向images添加一个<img />标签; animal是animals中的值的占位符 const images = []; for(const animal in animals){ const image = ( <img key= {animal} className='animal' alt={animal} src= {animals[animal].image} aria-label= {animal} role='button' onClick= {displayFact} /> ); images.push(image); } const animalFacts = ( <div> <h1> {title === '' ?'Click an animal for a fun fact':title}// 这里也可以写成title||'Click an animal for a fun fact'因为只有true或false两个选项,不需要使用三元运算符 </h1> {showBackground && background} <div className='animals'>{images}</div> <p id='fact'> </p> </div> ); // 添加事件 function displayFact(e) { const animalName = e.target.alt; const optionIndex = Math.floor(Math.random()*animals[animalName].facts.length); const fact = animals[animalName].facts[optionIndex]; const p = document.getElementById('fact'); p.innerHTML = fact; } root.render(animalFacts); ``` # 参考资料 - [Animal Fun Facts](https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-front-end-development/tracks/fscj-22-react-part-i/modules/wdcp-22-jsx-752c2293-9f61-412a-92e2-70ad6e01a0a7/projects/js-react-animal-fun-facts)