eg:
类组件:
1 2 3 4 5 6 7 8 9 10 11 12 13
| class ProfilePage extends React.Component { showMessage = () => { alert('Followed ' + this.props.user); };
handleClick = () => { setTimeout(this.showMessage, 3000); };
render() { return <button onClick={this.handleClick}>Follow</button>; } }
|
函数式组件:
1 2 3 4 5 6 7 8 9 10 11 12 13
| function ProfilePage(props) { const showMessage = () => { alert('Followed ' + props.user); };
const handleClick = () => { setTimeout(showMessage, 3000); };
return ( <button onClick={handleClick}>Follow</button> ); }
|
在React中props是不可变的,所以它们永远不会改变,然而,类组件中,this是且永远是可变的
类组件中this存在的意义:React本身随着时间推移而改变,以便你可以在渲染方法以及生命周期方法中得到最新的实例.
如果希望类组件中能在一次特定渲染中捕获那一次渲染所用的props或者state,可以使用闭包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class ProfilePage extends React.Component { render() { const props = this.props;
const showMessage = () => { alert('Followed ' + props.user); };
const handleClick = () => { setTimeout(showMessage, 3000); };
return <button onClick={handleClick}>Follow</button>; } }
|
函数式组件想捕获最新的props和state?
用useRef
1 2 3 4 5 6 7 8 9 10 11 12
| function MessageThread() { const [message, setMessage] = useState('');
const latestMessage = useRef(''); useEffect(() => { latestMessage.current = message; });
const showMessage = () => { alert('You said: ' + latestMessage.current); };
|
总结于: