Return React JS 中 Array 的多个 HOC 组件

Return multiple HOC components from Array in React JS

我正在尝试从任何数组中声明并 return 多个 HOC,但一直被 return 编辑为 "Functions are not valid as a React child." 错误。有没有人 运行 以前处理过这个问题?

JS:

....

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

const withRequestAnimationFrame = () => WrappedComponent => {
  class RequestAnimationFrame extends Component {
    state = {
      timeStamp: 0,
      newItem: "Test"
    };

    componentDidMount() {
      const min = 1;
      const max = 100;
      const rand = Math.floor(Math.random() * (max - min + 1)) + min;
      this.setState({ timeStamp: this.state.timeStamp + rand });
    }

    render() {
      return (
        <WrappedComponent {...this.state} {...this.props} />
      )
    }
  }
  return RequestAnimationFrame;
};

const App = ({ timeStamp, newItem }) => (
  <div style={styles}>
    <h1>{timeStamp}</h1>
    <p>{newItem}</p>
  </div>
);

const arrayItems = ["EnhancedApp", "EnhancedApp2"];
const Products = ({ items }) => {
  return (
    items.map((item, index)  => (
      item = withRequestAnimationFrame()(App)
    ))
  )
};

function Product() {
  return (
    <div>
      <Products items={arrayItems} />
    </div>
  )
}

render(<Product />, document.getElementById("root"));
  1. 这一行是问题所在:

    item = withRequestAnimationFrame()(App)
    

    你在那里做的是分配 withRequestAnimationFrame()(App) 的结果 对项目的功能绝对不是你想要的。我假设你想 在那里渲染 withRequestAnimationFrame 组件的多个实例。你可以 这样做:

    items.map((item, index)  => (
        const NewComponent = withRequestAnimationFrame(item)(App);
        return <NewComponent key={index}/>
    ))
    
  2. 第二个问题是您没有将 item prop 传递给包装组件。 要传递项目道具,您应该这样做:

    const withRequestAnimationFrame = (item) => WrappedComponent => {
       class RequestAnimationFrame extends React.Component {
           state = {
               timeStamp: 0,
               newItem: item
           };