react之组件类型

1、构造函数组件
构造函数组件,可接受外部传入的参数props,生成并返回一个React元素(伪DOM)。
例如,以下,Greeting做为一个组件,接受传入的参数name,并返回一个内容已填充的p标签。vue

function Greeting (props) {
   return (
      <p> {props.name},how are you? </p>
   )
}

const element = <Greeting name="Agnes" />
ReactDOM.render(
  element,
  document.getElementById('root')
)

2、class关键字组件
react中class组件的书写方式跟es6中类的书写方式很是接近,能够经过React.Compnent进行建立。与函数组件不一样的是,该组件能够进行复杂逻辑的处理,既能够接受外部参数props,也能够拥有本身的state,用于组件内的通讯。react

class HighGreeting extends React.Component {
   constructor(props){
     super(props);
     this.state={
       inputValue: this.props.name
     } 
     this.handleInputChange = this.handleInputChange.bind(this);
   }
   render () {
     return (
        <input type="text" onChange="handleInputChange"/>
        <p>{this.state.inputValue},how are you?</p>
     )
   }
   handleInputChange(e){
      let value = e.target.value;
      this.setState({
         inputValue: value
      })
   }
} 

const element = <HighGreeting name="Agnes" />
ReactDOM.render(
  element,
  document.getElementById('root')
)

上面的组件,接收props参数做为初始值,当用户输入时,会实时更新。es6

  1. class关键字组件内部能够定义state,至关于vue组件内的data,更改时须要调用this.setState,每次调用该方法时,都会执行render方法,自动更新组件。如上图,监听input的onchange事件,实时更改inputValue的值并展现。
  2. 须要注意的是,props不只能够传递值,还能够传递函数。(这一点跟vue不同,后面的文章会再细讲。)
相关文章
相关标签/搜索