简体   繁体   English

将代码分离为函数并调用它不会呈现

[英]Separating the code into a function and calling it doesn't render

This works perfectly fine. 这完全没问题。 Now, I would like to incorporate this into a function and just call the function within my expression. 现在,我想将它合并到一个函数中,并在我的表达式中调用该函数。 It doesn't work. 它不起作用。

Working code: 工作代码:

 render: function() {
      return (
        <div>
          {this.props.list.map(function(listValue){
            return <p>{listValue}</p>;
          })}
        </div>
      )
    }
  });

  ReactDOM.render(<List list={[1,2,3,4,5]} />, document.getElementById('app'));

code with the function (doesn't work): 具有该功能的代码(不起作用):

   var List = React.createClass({
    addText: function()
    {
         this.props.list.map(function(listValue){
            return <p>{listValue}</p>;
        });
    },
    render: function() {
      return (
        <div>
         {this.addText()}
        </div>
      )
    }
  });

  ReactDOM.render(<List list={[1,2,3,4,5]} />, document.getElementById('app'));

You've extracted the call to map into another function and maybe assumed the return call inside it was sufficient to return the result of the whole call (it just returns the mapped value for that iteration of map). 你已经提取的调用map到另一个函数, 也许假定return调用里面足以恢复整个调用的结果(它只是返回的映射值映射该迭代)。

You just need to return the result of your map in your addText function: 您只需要在addText函数中返回地图的结果:

var List = React.createClass({
    addText: function()
    {
        return (  // <------ADD THIS
           this.props.list.map(function(listValue){
            return <p>{listValue}</p>;
          })
        );  //<<-----DON'T FORGET TO CLOSE OFF THE NEW BRACKET
    },
    render: function() {
      return (
        <div>
         {this.addText()}
        </div>
      )
    }
  });

Tnx @Thomas altmann , I forgot to make another return prior to my first return Tnx @Thomas altmann ,我在第一次回来之前忘了再回来

var List = React.createClass({
    addText: function()
    {
         return (this.props.list.map(function(listValue){
            return <p>{listValue}</p>;
        })
         );
    },
    render: function() {
      return (
        <div>
         {this.addText()}
        </div>
      )
    }
  });

  ReactDOM.render(<List list={[1,2,3,4,5]} />, document.getElementById('app'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM