【问题标题】:React is showing "Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render"React 显示“函数作为 React 子级无效。如果您从渲染返回 Component 而不是 <Component />,则可能会发生这种情况”
【发布时间】:2020-02-20 10:45:34
【问题描述】:

以下是 game.jsapp.js 主文件:

//Heres the game file//

import React, { Component } from "react";

class Game extends Component {
  constructor(props) {
    super(props);
    this.state = { num: 0 };
    this.numPicker = this.numPicker.bind(this);
  }
  numPicker(e) {
    let rand = Math.floor(Math.random() * this.props.maxNum);
    return rand;
  }
  render() {
    return (
      <div>
        <h1>Hellow World {this.numPicker}</h1>
      </div>
    );
  }
}

export default Game;



//Heres the main file://


import React from "react";

import "./App.css";
import Game from "./game";

function App() {
  return (
    <div className="App">
      <Game maxNum={1} />
    </div>
  );
}

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

game.js 文件中,我在 H1 中使用了 numPicker 函数。现在我收到此错误:

警告:函数作为 React 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用这个函数而不是返回它。

【问题讨论】:

  • 错字:this.numPicker()。建议以拼写错误关闭。

标签: javascript reactjs


【解决方案1】:

您需要调用 numPicker 函数,该函数返回可以呈现的数据

<h1>Hellow World {this.numPicker()}</h1>

【讨论】:

猜你喜欢
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多