class的方式创建组件

创建组件:    
    1、使用class创建的类,通过extends关键字继承React.Component之后,这个类就是一个组件的模板了
        注意:
            ① No `render` method found on the returned component instance you may have forgotten to define `render`.
       通过以上报错,在class实现的组件内部,我们必须定义一个render函数
            ② Nothing was returned from render. This usually means a return statement is missing.  Or, to render nothing, return null.
         需要return 一个返回值
            ③ 使用class创建的组件,可以直接使用this.props来直接访问,不需要预先定义props
            ④ this.props中的属性都是只读的
class Hello2 extends React.Component {
  render() {
    return (
      <div>
        创建组件的第二种方式:这是使用class创建的组件
        <h1>外界传过来的数据是:{JSON.stringify(this.props)}</h1>
      </div>
    );
  }
}
  渲染组件: 
  1、如果想要引用这个组件,可以把类的名称以标签形式导入到jsx中使用。
 
ReactDOM.render(
  <div>
    <Hello name="张三" age={20}></Hello>
    <Hello2 address="北京天安门广场" info="吃炸鸡"></Hello2>
  </div>,
  document.getElementById("app")
);
 
2、运行结果:
    
注意事项:
   1、如果使用了extends实现了继承,那么在constructor的第一行
     一定要显示调用一下super(),super()表示父类的构造函数
  2、在constructor中,如果想要访问props属性,不能直接使用
     this.props,而是需要在constructor的构造器参数列表中,显示的
     定义props参数来接收,才能正常使用
class Hello2 extends React.Component {
  constructor(props1) {
    super(props1);
    console.log(props1);
  }
  render() {
    return (
      <div>
        创建组件的第二种方式:这是使用class创建的组件
        <h1>外界传过来的数据是:{JSON.stringify(this.props)}</h1>
      </div>
    );
  }
}
 

猜你喜欢

转载自www.cnblogs.com/wangyfax/p/13167549.html