React不会创建所需的元素

时间:2016-09-19 18:52:03

标签: javascript reactjs

我有以下代码。它根本不渲染fullRecipe项目,但我在这里看到没有错。我在学习这个框架时遇到了麻烦,在问过没人知道发生了什么之后......你看到了什么错了吗?

谢谢

class Index extends React.Component {
  constructor() {
    super();
  }
  render() {
    var list_results = this.props.recipes.map(function(recipe, index){
        console.log(index);  //Happens
        console.log(recipe); //Happens
        return (<fullRecipe recipe={recipe}></fullRecipe>);
    });
    return (<ul>{this.list_results}</ul>)
  }
}
function fullRecipe(props) {
    console.log(props || "no props"); // Doesnt happen
    return (<li><div class="delete-button">Delete</div>{props.name} - {props.ingredients}</li>);
}

2 个答案:

答案 0 :(得分:2)

fullRecipe需要成为Index类的一部分或者成为另一个组件。

您还使用this.list_results,这应该只是list_resultsthis是整个班级的背景,而varrender()的本地语境。

最简单的方法是:

class Index extends React.Component {
  constructor() {
    super();
  }
  fullRecipe() {
    return (<li><div class="delete-button">Delete</div>{this.props.name} -   {this.props.ingredients}</li>);
  }

  render() {
    var list_results = this.props.recipes.map((recipe, index) => this.fullRecipe(recipe));
    return (<ul>{list_results}</ul>)
  }
}

修改

我不确定我对上述内容的看法。实际上,它应该是两个组成部分,而且都不需要是有状态的。

//Index.js
export default const Index = ({ recipes }) => {
  return (
    <ul>
      {
        recipes.map( ({ ingredients, name }, index) => {
          return <Recipe key={index} ingredients={ingredients} name={name} />
        })
      }
    </ul>
  );
}

//Recipe.js
export default const Recipe = ({ ingredients, name }) => {
  return (
    <li>
      <button className="delete-button">Delete</button>
      {name} - {ingredients}
    </li>
  );
}

答案 1 :(得分:0)

错误使用功能/组件

您可以创建名为fullRecipe的组件来显示信息,也可以将函数fullRecipe带到Index组件。

点击此链接https://facebook.github.io/react/docs/multiple-components.html