Javascript 为什么在setTimeout为0的情况下聚焦文本区域不起作用?

Javascript 为什么在setTimeout为0的情况下聚焦文本区域不起作用?,javascript,html,reactjs,Javascript,Html,Reactjs,我有一个按钮来编辑一个div,它把它变成一个文本区域。我之所以使用此代码,是因为我希望光标在开始编辑后显示在文本区域的末尾: constructor(props) { super(props); this.state = { body: "asdf" }; this.messageItemRef = React.createRef(); } componentDidMount() { let length = this.state.body.length; setT

我有一个按钮来编辑一个div,它把它变成一个文本区域。我之所以使用此代码,是因为我希望光标在开始编辑后显示在文本区域的末尾:

constructor(props) {
  super(props);

   this.state = { body: "asdf" };

  this.messageItemRef = React.createRef();
}

componentDidMount() {
  let length = this.state.body.length;

  setTimeout(() => {
    this.messageItemRef.current.focus();
    this.messageItemRef.current.setSelectionRange(length, length);
  }, 0);
}


render() {
  return ( 
    <textarea ref={this.messageItemRef} value={this.state.body} />
  );
}
构造函数(道具){
超级(道具);
this.state={body:“asdf”};
this.messageItemRef=React.createRef();
}
componentDidMount(){
让长度=this.state.body.length;
设置超时(()=>{
this.messageItemRef.current.focus();
this.messageItemRef.current.setSelectionRange(长度,长度);
}, 0);
}
render(){
报税表(
);
}
我随机决定尝试0的
setTimeout
,因为它只在我单击编辑按钮时起作用,而在我使用热键编辑它时不起作用

我想知道,为什么需要设置0的超时?如果我去掉它,当我点击按钮时,它只聚焦文本区域的末端,而不是当我使用键盘热键时


为什么会这样?

再多显示一些代码,伙计。再多显示一些代码,伙计。