我希望在输入字段呈现后立即关注它。缺点是我无法在startEdit方法中专注于它,因为在我想要聚焦的那一刻没有对元素的引用,所以this.editField是未定义的。我可以创建<Input />
组件并实现聚焦于它的componentDidMount方法,但我想知道是否有更简洁的方法来做到这一点?
class TodoItem extends React.Component<IProps, IState> {
editField ?: HTMLInputElement;
constructor() {
super();
this.state = {
isEditActive: false
};
}
private startEdit(): void {
this.setState({isEditActive: true});
this.editField.focus();
}
private finishEdit(): void {
this.setState({isEditActive: false});
}
public render(): JSX.Element {
const {text, deleteTodo} = this.props;
const {isEditActive} = this.state;
return(
<li className='todo-item'>
{isEditActive ?
<input ref={(input) => { this.editField = input; }} onBlur={this.finishEdit} type='text'/>
: text
}
<span onClick={deleteTodo} className='delete'>X</span>
<span onClick={this.startEdit} className='edit'>Edit</span>
</li>
);
}
}