2016-09-28 12 views
0

私はinput要素を持つコンポーネントを持っていますが、私は初期値を設定するためにdefaultValueを使います。 最初にその要素にフォーカスを当てて全体の値を選択したいのですが、componentDidMountが呼び出されたときにdefaultvalueが設定されていないようです。リアクション入力defaultValueフォーカスと選択

ヒントはありますか?

私は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のメソッドを使用していないだろうrender/renderToString。これらのapisは「脱出ハッチ」であり、使用法は推奨されていません。

関連する問題