javascript - 我可以在 React 组件中使用相同的组件吗?

标签 javascript reactjs

import React from 'react';

class Feladatlista extends React.Component{
    constructor(props){
        super(props);
    }
    feladatok = () => {
        if(this.props.fl.length){
            this.props.fl.map(fl => {
                return <Feladatlista tipus={fl.tipus} nev={fl.nev} rang={fl.rang} fl={fl.fl}/>
            })
        }
    }
    render(){
        return(
            <div>
                <div className={this.props.tipus}>
                    <p>{this.props.nev}</p>
                    <p>{this.props.rang}</p>
                </div>
                <div className='gyerek'>
                    {this.feladatok}
                </div>
            </div>
        )
    }
}
export default Feladatlista;

这是我的代码。我的计划是,拥有一个包含嵌套对象的数据库,其中我使用彼此连接的相同组件推送数据。像这样:

const feladat = [
  {név: 'asd',
  tipus: 'a',
  rang: '1',
  fl:[
    {név: 'dd',
    tipus: 'a',
    rang: '1',
    fl: []},
    {név: 'eded',
    tipus: 'a',
    rang: '2',
    fl: [
      {név: 'das',
      tipus: 'a',
      rang: '1',
      fl: []},
      {név: 'dasd',
      tipus: 'a',
      rang: '2',
      fl: [
        {név: 'dasd',
        tipus: 'a',
        rang: '1',
        fl: []
        }]
      }]
    }]
  }
]

这样,在主程序(App.js)中我定义了第一个元素,并且它循环遍历所有数组。但我收到错误消息:index.js:2178 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. 。问题是我想在组件中使用相同的组件,还是其他的?

最佳答案

首先需要从feladatok返回数据, 其次,您需要从渲染中调用该函数,例如 this.feladatok()

class Feladatlista extends React.Component {
  feladatok = () => {
    if (this.props.fl.length) {
      return this.props.fl.map((fl, index) => {
        return (
          <Feladatlista
            key={index}
            tipus={fl.tipus}
            nev={fl.nev}
            rang={fl.rang}
            fl={fl.fl}
          />
        );
      });
    }
    return null;
  };
  render() {
    console.log(this.props.fl);
    return (
      <div>
        <div className={this.props.tipus}>
          <p>{this.props.nev}</p>
          <p>{this.props.rang}</p>
        </div>
        <div className="gyerek">{this.feladatok()}</div>
      </div>
    );
  }
}

<强> Working demo

关于javascript - 我可以在 React 组件中使用相同的组件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50193389/

相关文章:

javascript - 什么是exports.displayName =(未定义: ?字符串);意味着 react native ?

javascript - 从 React Native 导入 StyleSheet 时未定义不是对象

reactjs - Jest.js 测试不适用于 Intl.NumberFormat

javascript - jQuery Mobile 在新页面上打开单个 json 对象

javascript - 在菜单外单击时隐藏的下拉菜单

javascript - FireFox 是否缓存 jquery.ajax 返回?

javascript - 如果我需要在 React 组件之后设置 State,如何对服务器的失败响应使用react?

php - 不想刷新并保留最后插入的值

javascript - jQuery 如何在表单发布返回后触发事件?

reactjs - 在 Elastic Beanstalk 中构建 React 应用程序