RecatJs无法与两个组件进行通信

时间:2017-07-09 16:55:19

标签: reactjs

如果我的问题很愚蠢,我是新来的,所以要提前道歉。

项目是我从App.js获得的数组

(Project.js)

import React, { Component } from 'react';
import ProjectItem from './ProjectItem'

class Projects extends Component {
  render() {
    //====== PROJECTS IS AN ARRAY IAM GETTING FROM App.js====
    let projectItems;
    if(this.props.projects){
      projectItems = this.props.projects.map(project => {
        return(
          <ProjectItem key={project.title} project={project} />

        );
      }); // projects map end
    }//==if end
    // ====== RETURN PROJECTS ======
    return (
      <div className="Projects">
          <h1>Projects</h1>
          <p>{this.props.projects[0].title}</p>
      </div>
    );
  }
}

export default Projects;

在这里,我无法从Project.js获取道具

ProjectItem.js

import React, { Component } from 'react';

class ProjectItem extends Component {
  render() {
    console.log(this.props);
    return (
      <li className="Project">
        {this.props.project.title}

      </li>
    );
  }
}

export default ProjectItem;

请提前帮助和谢谢。

1 个答案:

答案 0 :(得分:0)

虽然您认为已经通过projects array映射创建了“项目”列表,但除非您从“组件”返回,否则您将无法显示道具。

您需要将projectItems添加到返回函数,例如

import React, { Component } from 'react';
import ProjectItem from './ProjectItem'

class Projects extends Component {
  render() {
    //====== PROJECTS IS AN ARRAY IAM GETTING FROM App.js====
    let projectItems;
    if(this.props.projects){
      projectItems = this.props.projects.map(project => {
        return(
          <ProjectItem key={project.title} project={project} />

        );
      }); // projects map end
    }//==if end
    // ====== RETURN PROJECTS ======
    return (
      <div className="Projects">
          <h1>Projects</h1>
          {projectItems}
      </div>
    );
  }
}

export default Projects;