反应警告:函数作为反应孩子无效 [英] React warning: Functions are not valid as a React child
问题描述
我有这个反应组件.这不是正确渲染,而是收到诸如
之类的烦人警告函数作为 React 子元素无效.如果您返回 Component 而不是从渲染中返回,则可能会发生这种情况.或者,您可能打算调用此函数而不是返回它.
这是我的组件.我在这里做错了什么?
import React, { Component } from 'react';类 Squares 扩展组件 {构造函数(道具){超级(道具);this.createSquare = this.createSquare.bind(this);}创建方(){让缩进 = [],行 = this.props.rows,cols = this.props.cols;让 squareSize = 50;for (让 i = 0; i < 行; i++) {for (让 j = 0; i < cols; j++) {让 topPosition = j * squareSize;让 leftPosition = i * squareSize;让 divStyle = {顶部:topPosition+'px',左:leftPosition+'px'};indents.push(<div style={divStyle}></div>);}}返回缩进;}使成为() {返回 (<div>{this.createSquare()}
);}}导出默认方块;
更新
@Ross Allen - 进行更改后,渲染方法似乎处于无限循环中,可能会导致内存崩溃
您需要调用 createSquare
,现在您只是传递对函数的引用.后面加括号:
render() {返回 (<div>{this.createSquare()}
);}
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
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>
);
}
这篇关于反应警告:函数作为反应孩子无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!