相信学习React的都是有过一定了解的,React页面都是一个个组件构成的,所以写React也就是写一个个组件的过程。
目前,从写法上来说React组件主要有两种写法,一种是函数式(Functional)组件,一种是继承类(Class)组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function Welcome(props) { return <h1>Hello, {props.name}</h1> }
const Welcome = (props) => { return ( <h1>Hello, {props.name}</h1> ) } export default Welcome
// Class class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
export default Welcom
|
按照React组件的功能可以分为有状态组件和无状态组件。无状态组件一般使用函数式组件即可。
我的建议是,如果不清楚是用哪一种写法去编写组件,可以先使用函数式组件。在编写过程中如若发现需要使用state或者组件生命周期,再将此组件改成继承类组件。下面是一个比较完整的继承类组件架子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class MyComponent extends Component { constructor (props) { super(props) this.state = { ... } this.handleClick = this.handleClick.bind(this) }
componentWillMount () {} componentDidMount () {} componentWillReceiveProps () {} componentWillUpdate () {} componentWillUnmount () {}
handleClick() { this.setState({ ... }) }
render() { return ( <div onClick={this.handleClick}> </div> ) } }
MyComponent.defaultProps = {} MyComponent.propTypes = {}
export default MyComponent
|
需要注意点:
无论哪种写法,return中必须被一个标签包裹,这是jsx语法要求的。
函数式组件也可以设置defaultProps和propTypes。
函数式组件中不能访问this。
可以声明变量值为jsx,如:let a = <div></div>