import React, { useCallback, useState, memo } from 'react';
import ReactDOM from 'react-dom';
var SubFunctionComponent = memo((props) => {
console.log('SubFunctionComponent render');
return (
<div>
<h1>我是函数组件,数据从函数组件传过来,值是 {props.count}</h1>
<button onClick={props.onClick}>function +1</button>
</div>
)
})
class SubClassComponent extends React.PureComponent {
render() {
console.log('SubClassComponent render');
return (
<div>
<h1>我是类组件,数据从函数组件传过来,值是 {this.props.count} </h1>
<button onClick={this.props.onClick}>class +1</button>
</div>
)
}
}
function AppFunction() {
const [count, setCount] = useState(0);
console.log('App组件 render');
const [inputVal, setInputVal] = useState(0);
// 函数组件要使用 useCallBack 返回一个带缓存的回调 、 相当于 class 组件的 classField
const handleClick = useCallback(() => setCount(count + 1), [count]);
return (
<div className="App">
<SubClassComponent count={count} onClick={handleClick} />
<SubFunctionComponent count={count} onClick={handleClick} />
<input
value={inputVal}
type="number"
onChange={(e) => setInputVal(parseInt(e.target.value) || 0)} />
</div>
);
}
class AppClass extends React.Component {
state = {
count: 0,
inputVal: 0
}
// 使用 class field 方式来解决
handleClick = () => {
const { count } = this.state;
this.setState({ count: count + 1 })
}
render() {
console.log('主组件 render');
const { count, inputVal } = this.state;
return (
<div className="App">
<SubClassComponent count={count} onClick={this.handleClick} />
<input
value={inputVal}
type="number"
onChange={(e) => this.setState({ inputVal: parseInt(e.target.value) || 0 })} />
</div>
);
}
}
ReactDOM.render(
(<><AppFunction /><AppClass /></>),
document.getElementById('root')
);