1. 创建方式
// 写法一
const Hello = (props) => {
return <div>{props.message}</div>
}
// 写法二
const Hello = props => <div>{props.message}</div>
// 写法三
function Hello(props) {
return <div>{props.message}</div>
}
2. 函数组件代替类组件
面临的问题
- 函数组件没有state => React v16.8.0推出Hooks API,其中的一个API叫做useState可以解决问题
- 函数组件没有生命周期 => React v16.8.0推出Hooks API,其中的一个API叫做useEffect可以解决问题
我们对比一下两种组件实现 n + 1 的例子
类组件
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
n: 0
}
}
addNum = () => {
this.setState({n: this.state.n + 1})
}
render() {
return (
<div className='App'>
<span>n:{this.state.n}</sp