简体   繁体   English

在 React.js 中通过 createElement 向元素添加组件

[英]adding component to element made through createElement in React.js

I want to add a Like button to my elements that I add through a forEach creating elements from an API call.我想向我的元素添加一个 Like 按钮,我通过一个 forEach 添加来自 API 调用的元素。 So I imported a Like Button I made as a component and tried adding it to the card like this:所以我导入了一个我作为组件制作的 Like Button,并尝试将其添加到卡片中,如下所示:

import LikeBtn from "./LikeBtn/LikeBtn";      

const likeBtn = document.createElement("span");
likeBtn.className = "imgcards__like-btn";
likeBtn.innerHTML = LikeBtn;

but it just comes out like this: result但结果是这样的:结果

LikeBtn component and rest of code for reference: LikeBtn组件和rest的代码供参考:

 import React from "react"; import { AiFillHeart, AiOutlineHeart } from "react-icons/ai"; const LikeBtn = () => { let liked = this.props.liked || false; let count = this.props.count || true; let color = "lightcoral"; if (liked) { return ( <span class="likebtn__icon" style={{ color: color }} onClick={this.onClick} > <AiFillHeart /> {count? count: ""} </span> ); } else { return ( <span class="likebtn__icon" onClick={this.onClick}> <AiOutlineHeart /> {count? count: ""} </span> ); } }; export default LikeBtn;

 import React from "react"; import "./ImageCards.css"; import LikeBtn from "./LikeBtn/LikeBtn"; function populateList(items) { items.forEach((item) => addItem(item)); } function addItem(item) { const card = document.createElement("div"); card.className = "imgcards__card"; const cardContent = document.createElement("div"); cardContent.className = "imgcards__card-content"; const title = document.createElement("h1"); title.className = "imgcards__title"; title.innerHTML = item.title; const date = document.createElement("p"); date.className = "imgcards__date"; date.innerHTML = item.date; const image = document.createElement("img"); image.className = "imgcards__image"; image.src = item.hdurl; const likeBtn = document.createElement("span"); likeBtn.className = "imgcards__like-btn"; likeBtn.innerHTML = LikeBtn; cardContent.appendChild(title); cardContent.appendChild(date); cardContent.appendChild(image); cardContent.appendChild(likeBtn); card.appendChild(cardContent); document.getElementById("imgcards__cards-container").appendChild(card); } export default class ImageCards extends React.Component { async componentDidMount() { fetch( "https://api.nasa.gov/planetary/apod?count=20&api_key=lwtGe8ifpAENLITuYZ0b1gqxkdhZux9u2OdvlfB4", { method: "GET", headers: { "content-type": "application/json", }, } ).then((response) => response.json()).then((data) => populateList(data)); } render() { return ( <div className="imgcards"> <div className="imgcards__cards-container" id="imgcards__cards-container" ></div> </div> ); } }

This was my best idea for adding a like button that's responsive for each item, so other than my issue if you have a better way of doing it pls let me know.这是我添加一个对每个项目都有响应的赞按钮的最佳想法,所以除了我的问题,如果你有更好的方法,请告诉我。 Thank you!谢谢!

Avoid direct DOM manipulation as Chris stated.正如 Chris 所说,避免直接的 DOM 操作。 Regarding your case, It's better to use.map() on the items list.关于您的情况,最好在项目列表上使用 .map() 。 I wrote a quick sample based on your API request that you can start working with.我根据您可以开始使用的 API 请求编写了一个快速示例。 See below:见下文:

    import React, {useState, useEffect} from "react";
    import "./style.css";
    
    export default function App() {
      const [data, setData] = useState([])
    
      useEffect(() => {
        fetch(
          "https://api.nasa.gov/planetary/apod?count=20&api_key=lwtGe8ifpAENLITuYZ0b1gqxkdhZux9u2OdvlfB4",
          {
            method: "GET",
            headers: {
              "content-type": "application/json",
            },
          }
        )
          .then((response) => response.json())
          .then((data) => setData(data));
      }, [])
    
      return (
        <div>
        {data.map((item, index) => (
    
          <div className="imgcards__title"> 
          {
         <li>{item.title}  {item.date}</li>
    }
        </div>
       
        ))
      }
        </div>
       
      );

}

You can also add the like button that you mentioned with the other html elements inside the.map() scope and apply whatever logic you wish to add using onClick() or other functionalities.您还可以在.map() scope 中添加您提到的与其他 html 元素一起提到的类似按钮,并使用 onClick() 或其他功能应用您希望添加的任何逻辑。 I recommend reading the React documentation on how to use the map function with list to display data, here .我建议阅读 React 文档,了解如何使用 map function 和列表来显示数据,这里 Edit: don't forget add a key to each child as well as each element inside children.编辑:不要忘记为每个孩子以及孩子中的每个元素添加一个键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM