首页 > 解决方案 > 返回功能组件内的组件

问题描述

import React from "react";
import HeroAsideItems from "./components/HeroAsideItems";
import "./css/heroAsideCircles.css";

function HeroAsideCircles(props) {
 
  const renderHeroAsideItems = () => {
    // Turn the prop object into an array of its keys using Object.keys(props)
    //Then map/loop over the array of keys returned by Object.keys
    //The argument "keys" holds and array of keys and "i" hold the index of the array so it is the iterable. It will increase for every key in the array starting at 0.
    Object.keys(props).map((keys, i) => {
      // Test for valid prop inputs. I want all valid props to follow the naming convention of `hoverTxt${someNumber}`
      // validPropCount takes the key argument passed by map (which holds the keys of the prop object in an array) and checks to see if it includes `hoverTxt${and some number within the amount of entries in the array}`
      // validPropCount will return true if it includes those values or false if it does not
      const validPropCount = keys.includes(`hoverTxt${i + 1}`);
      //If validPropCount returns true return and assign the <HeroAsideItems /> component the current prop value being passed in the loop to the component's hoverTxt (which is responsible for the text of the component)
      if (validPropCount) {
        console.log("valid");
        console.log(Object.values(props)[i]);
        return <HeroAsideItems key={i} hoverTxt={Object.values(props)[i]} />;
        // else if validPropCount returns false do not return a component
      } else {
        console.log("not valid");
      }
    });
  };

  return (
    <div className="hACContainer">
      {renderHeroAsideItems()}
    </div>
  );
}

export default HeroAsideCircles;

我正在尝试在 renderHeroAsideItems 函数中返回组件。这就是我尝试这样做的方式,但它不起作用。什么是正确的语法

标签: reactjsreact-hookscreate-react-appreact-propsreact-functional-component

解决方案


您没有返回 Object.keys(props).map((keys, i) => {}).

它应该是return Object.keys(props).map((keys, i) => {})


推荐阅读