我需要确保在满足以下条件时关注输入元素:
问题:我是否需要将我的代码放入两者中componentDidUpdate,componentDidMount或者仅仅componentDidUpdate是足够的?
private makeSureInputElementFocused() {
if (this.props.shouldGetInputElementFocused && this.inputElement !== null) {
this.inputElement.focus();
}
}
componentDidMount() {
this.makeSureInputElementFocused(); // <-- do i need this?
}
componentDidUpdate() {
this.makeSureInputElementFocused();
}
Run Code Online (Sandbox Code Playgroud)
Mur*_*göz 24
你必须使用两者.
在装入组件后立即调用componentDidMount().需要DOM节点的初始化应该放在这里.如果需要从远程端点加载数据,这是实例化网络请求的好地方.在此方法中设置状态将触发重新渲染.
更新发生后立即调用componentDidUpdate().初始渲染不会调用此方法.
您也可以将它放入render()适合您的情况的方法中,因为您总是想要检查焦点.然后,你不必把它放入componentDidMount()和componentDidUpdate()
每个条件都要求您将代码分别放在1个函数内:
componentDidMountcomponentDidUpdate因此,您必须将它们放置在两个函数中。
另一种选择是在setState()内部调用componentDidMount,从而componentDidUpdate被调用。
组件DidMount()
componentDidMount()将在组件安装后立即调用。这个方法只会渲染一次,所有需要 DOM 节点的初始化都应该在这里进行。在此方法中设置状态将触发重新渲染。
组件DidUpdate()
组件DidUpdate()每次更新发生时都会立即调用初始渲染不会调用此方法。
您可以从下面的示例中了解更多
import React from 'react';
class Example extends React.Component{
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
//This function will call on initial rendering.
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render(){
return(
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
)
}
}
export default Example;
Run Code Online (Sandbox Code Playgroud)
你可以通过注释和取消注释这两种方法来理解。
componentDidUpdate在初始渲染时不会被调用(请参阅https://reactjs.org/docs/react-component.html#componentdidupdate),因此您可能必须像示例中那样调用它两次。
| 归档时间: |
|
| 查看次数: |
15264 次 |
| 最近记录: |