通过函数在无状态组件中创建JSX

时间:2018-08-23 07:02:07

标签: javascript reactjs web-applications ecmascript-6 functional-programming

请参考下面的代码。有什么方法可以实现我的目标?

我试图基于Props值创建条件JSX,但是要在一个单独的函数中。

不确定如何使其工作。

import React from 'react';

function Greetings(props) {
  console.log(props);

  function showGreeting() {
    switch(props.message) {
      case '2':
        return "Howdy! Everything seems shiny.";
      case '3':
        return "Well well, who do we have here :)";
      case '4':
        return "Welcome back. We missed you!";
      case 'default':
        return "Hello there, Good Morning!";
    }
  }

  return (
    <div>
      {this.showGreeting}
    </div>
  )
}

export default Greetings;

最终结果是错误:

  

TypeError: Cannot read property 'showGreeting' of undefined

1 个答案:

答案 0 :(得分:1)

您正试图调用this.showGreeting,但是这里的this只是一个函数,不响应组件。

您必须使用<div>{showGreeting()}</div>(注意()会调用函数),因为此函数不是在函数上定义的,而是在函数定义期间定义的

相关问题