2016-09-28 83 views
0

我有一個帶有輸入元素的組件,我使用defaultValue來設置初始值。 我想要關注這個元素並且最初選擇整個值,但是當componentDidMount被調用時,似乎沒有設置默認值。React input defaultValue focus並選擇

您有任何提示嗎?

我使用window.setTimeout但我想避免在我的反應組件:

 public componentDidMount(): void { 
     if (this.props.focus) { 
      let tInput: HTMLInputElement = ReactDOM.findDOMNode(this).getElementsByTagName("input").item(0); 
      if (tInput) { 
       tInput.focus(); 
       // FixMe: defaultValue is set too late by react so i cant set selection instantly 
       if (this.props.defaultValue) { 
        window.setTimeout(
         () => {tInput.setSelectionRange(0, this.props.defaultValue.length); }, 
         100 
        ); 
       } 
      } 
     } 
    } 
+0

你可以發佈渲染調用嗎?你如何設置defaultValue? – Benjamin

回答

0

正常工作對我來說:

class MyComponent extends React.Component { 

    componentDidMount() { 
     const { myInput } = this.refs 
     myInput.focus() 
     myInput.select() 
    } 

    render() { 
     return (
      <input type='text' defaultValue='Foobar' ref='myInput' /> 
     ) 
    } 
} 

我不會用比其他任何reactDOM方法渲染/ renderToString。這些apis是「逃生艙」,不建議使用。