React warning: Functions are not valid as a React child

送分小仙女□ 提交于 2019-12-24 12:01:26

问题


I have this react component. This is not rendering properly but getting an annoying warning like

Functions are not valid as a React child. This may happen if you return a Component instead of from the render. Or maybe you meant to call this function rather than return it.

Here's my component. What am I doing wrong here?

import React, { Component } from 'react';

class Squares extends Component {   

    constructor(props){
        super(props);
        this.createSquare = this.createSquare.bind(this);
    }

    createSquare() {
        let indents = [], rows = this.props.rows, cols = this.props.cols;
        let squareSize = 50;
        for (let i = 0; i < rows; i++) {
            for (let j = 0; i < cols; j++) {
                let topPosition = j * squareSize;
                let leftPosition = i * squareSize;
                let divStyle = {
                    top: topPosition+'px', 
                    left: leftPosition+'px'
                };
                indents.push(<div style={divStyle}></div>);
            }   
          }
        return indents;
    }    

    render() {
      return (
        <div>
            {this.createSquare()}
        </div>
      );
    }
}

export default Squares;

UPDATE

@Ross Allen - After making that change, the render method seems to be in infinite loop with potential memory crash


回答1:


You need to call createSquare, right now you're just passing a reference to the function. Add parentheses after it:

render() {
  return (
    <div>
      {this.createSquare()}
    </div>
  );
}



回答2:


React uses JSX to render HTML and return function within render() should contain only HTML elements and any expression that needed to be evaluated must be within { } as explanied in https://reactjs.org/docs/introducing-jsx.html. But the best practice would be to do any operation outside return just inside render() where you can store the values and refer them in the return() and restrict usage of { } to just simple expression evaluation. Refer for In depth JSX integration with React https://reactjs.org/docs/jsx-in-depth.html

render() {
var sq = this.createSquare();
return (
  <div>
    {sq}
  </div>
);

Ross Allen's answer is also fine , the point is Inside JSX enclose any operation / evaluation inside { }




回答3:


You just need to remove () from your function call.

render() {
  return (
    <div>
        {this.createSquare}
    </div>
  );
}


来源:https://stackoverflow.com/questions/51220135/react-warning-functions-are-not-valid-as-a-react-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!