React map循环内调用函数时如何传递当前DOM元素作为参数
问题核心原因
- 你当前使用的是函数组件,函数组件内部
this默认是undefined,传入this根本无法获取到对应的td DOM元素 - 直接操作DOM修改innerHTML不符合React的声明式渲染逻辑,还存在XSS安全风险
- 不需要手动拼接HTML字符串,直接让工具函数返回React元素即可完成渲染
修复后的代码
import React from "react" import games from "../../assets/games" import './style.scss'; function SingleGame(props) { // 工具函数直接返回要渲染的内容,不需要传入DOM元素操作 function checkContent(content) { // 判断内容为数组时返回ul结构 if (Array.isArray(content)) { return ( <ul> {content.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> ) } // 非数组内容直接返回原值 return content } return ( <div className="singlegame" id={games[props.game].name}> <div className="singlegame--title"> {games[props.game].name} </div> <div className="singlegame--imagecontainer"> <img className="singlegame--imagecontainer-image" src={games[props.game].image} alt={games[props.game].name} /> </div> <table className="singlegame--table"> <tbody> {Object.keys(games[props.game].details).map(detail => ( <tr key={detail}> <th><strong>{detail}</strong></th> {/* 无需传this,直接调用函数获取返回的React元素渲染 */} <td>{checkContent(games[props.game].details[detail])}</td> </tr> ))} </tbody> </table> </div> ) } export default SingleGame
补充说明
- 如果数组元素存在唯一标识值,建议把li的key替换为该唯一值,不要用index,避免列表重排时出现渲染异常
- 特殊场景确实需要插入HTML字符串的话,可以使用
dangerouslySetInnerHTML,但优先选择React元素写法,安全性和可维护性更高
内容的提问来源于stack exchange,提问作者Phil Samson
相关产品推荐
相关产品推荐

