【问题标题】:Returning a component inside a functional component返回功能组件内的组件
【发布时间】:2021-06-12 13:04:57
【问题描述】:
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 函数中返回组件。这就是我尝试这样做的方式,但它不起作用。正确的语法是什么

【问题讨论】:

  • 返回Object.keys(props).map((keys, i) =&gt; { -> return Object.keys(props).map((keys, i) =&gt; {
  • atm renderHeroAsideItems() 正在返回未定义

标签: reactjs react-hooks create-react-app react-props react-functional-component


【解决方案1】:

您没有返回 Object.keys(props).map((keys, i) =&gt; {}) 的结果。

应该是return Object.keys(props).map((keys, i) =&gt; {})

【讨论】:

    猜你喜欢
    • 2016-02-15
    • 2020-07-29
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2021-06-09
    • 2020-12-10
    • 1970-01-01
    相关资源
    最近更新 更多