一、函数组件
函数组件类似一个纯函数,接受外部传入的参数,生成并返回一个React元素(伪DOM)。
例如,如下,Greeting作为一个组件,接受传入的参数name,并返回一个内容已填充的p标签。
function Greeting (props) { return ( <p> {props.name},how are you? </p> )}const element = <Greeting name="Agnes" />ReactDOM.render( element, document.getElementById('root'))
二、class组件
react中class组件的书写方式跟es6中类的书写方式非常接近,可以通过React.Compnent进行创建。与函数组件不同的是,该组件可以进行复杂逻辑的处理,既可以接受外部参数,也可以拥有自己的state,用于组件内的通信。
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参数作为初始值,当用户输入时,会实时更新。
- 每次定义子类的构造函数时,都需要调用super方法,因此所有含有构造函数的React组件中,构造函数必须以super开头。调用super相当于初始化this.props。
- class组件内部可以定义state,相当于vue组件内的data,更改时需要调用this.setState,每次调用该方法时,都会执行render方法,自动更新组件。如上图,监听input的onchange事件,实时更改inputValue的值并展示。
- 需要注意的是,props不仅可以传递值,还可以传递函数,甚至传递另一个组件。(这一点跟vue不一样,后面的文章会再细讲。)