Aya*_*yan 14 javascript reactjs
我无法自动对焦在此组件中呈现的输入标记.我在这里错过了什么?
class TaskBox extends Component {
constructor() {
super();
this.focus = this.focus.bind(this);
}
focus() {
this.textInput.focus();
}
componentWillUpdate(){
this.focus();
}
render() {
let props = this.props;
return (
<div style={{display: props.visible ? 'block' : 'none'}}>
<input
ref={(input) => { this.textInput = input; }}
onBlur={props.blurFN} />
<div>
<div>Imp.</div>
<div>Urg.</div>
<div>Role</div>
</div>
<div>
<button>Add goal</button>
</div>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏.
May*_*kla 21
有一个属性可用于自动对焦autoFocus,我们可以使用它来自动聚焦输入元素而不是使用ref.
使用autoFocus输入元素:
<input autoFocus />
我们也可以使用ref,但是使用ref我们需要在正确的位置调用focus方法,你在componentWillUpdate生命周期方法中调用它,在初始渲染期间不会触发该方法,而不是使用componentDidMount生命周期方法:
componentDidMount(){
this.focus();
}
Run Code Online (Sandbox Code Playgroud)
shouldComponentUpdate:始终在render方法之前调用,并且可以定义是否需要重新呈现或是否可以跳过重新呈现.显然,在初始渲染时永远不会调用此方法.只有在组件中发生某些状态更改时才会调用它.
一旦shouldComponentUpdate返回true,就会调用 componentWillUpdate.
componentDidMount:一旦执行了render方法,就会调用componentDidMount函数.可以使用此方法访问DOM,从而可以定义DOM操作或数据提取操作.任何DOM交互都应该始终发生在这里.
参考:https://facebook.github.io/react/docs/react-component.html
| 归档时间: |
|
| 查看次数: |
20500 次 |
| 最近记录: |