无法呈现简单的反应示例

Failed to render simple react example

const HiContainer => (props) {
  render{
    return(
       <h1>Hi {this.props.greet}</h1>
    )
  }
}

ReactDOM.render(
  <HiContainer greet="hi"/>
  document.getElementById('root')
);

这段代码有什么问题?很难调试我在控制台中看不到哪一行有问题。

还有什么时候需要使用constructor

您好像在使用功能组件,它会自动处理 render 方法。

代码应该是:

const HiContainer = (props) => (
  <h1>Hi {props.greet}</h1>
)

如果要为组件添加生命周期方法,需要将其转换为class组件。

你有一些语法错误,应该是

const HiContainer = (props) => {
  return(
    <h1>Hi {props.greet}</h1>
  )
}

可以简化为:

const HiContainer = props => <h1>Hi {props.greet}</h1>

你可能需要从基础学起,这是箭头函数: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

问题是,您以错误的方式使用了 arrow 函数。

应该是这样的const HiContainer = () => {}。 试试这个它会起作用:

const HiContainer = (props) => {
    return(
       <h1>Welcome {props.greet}</h1>
    )
}

ReactDOM.render(
    <HiContainer greet="hi"/>,
    document.getElementById('app')
);
使用stateful components时需要

constructor,并将信息存储在状态变量中,因为您使用的是stateless components,不需要constructor

检查 jsfiddle 工作示例:https://jsfiddle.net/ej2szg3a/

检查无状态函数组件:https://www.reactenlightenment.com/react-state/8.4.html