2017-11-09 9 views
0

ReactJSとMaterial UIを使用してアプリケーションを作成しています。 FormControlコンポーネント内にInputコンポーネントがあります。ユーザーがFormControlをクリックしたとき(ただしInputコンポーネントの外側にある場合)にInputコンポーネントに焦点を当てたいと思います。これはどのように達成できますか?私はレフリーで試してみましたが、私はそれを行うことができませんでした。問題は、コンテキストとクリックイベントがFormControl要素で取り扱われている方法であるかもしれない助けを事前にMUI入力コンポーネントがその領域外をクリックしたときにフォーカスを設定する

<FormControl 
    onClick={this.textInput.focus()} 
    style={{ display: 'block', cursor: 'text' }} 
> 
<Input 
    error={this.props.error} 
    disabled={this.props.disabled} 
    ref={(input) => { this.textInput = input; }} 
/> 
</FormControl> 

おかげ

+0

私が手に:未定義の 'フォーカス' プロパティを読み取ることができません。 – Anto

答えて

2

が、私はここでは2つの問題があると思う:

代わりにこれを試してみてください。まず、onClickの値は関数ではないので、まだ定義されていないrefに対して、コンポーネントがインスタンス化されるときにfocusが呼び出されます。 () => this.textInput.focus()を(あるいはそのための方法/インスタンスのプロパティを作成します。)

を第二に、あなたはrefを使用する場合withStyles高次の成分にInputコンポーネントをラップし、material-ui、それが参照する:あなたは、呼び出しをラップすることによってこの問題を解決することができますラップされたコンポーネントは、focusメソッドを持たない。代わりにinputRef小道具を使用すると、実際のinput DOM要素への参照が作成されます。このコードは動作するはずです

https://material-ui-next.com/customization/api/#internal-componentsを参照してください):

.. 
    <FormControl 
    onClick={() => this.textInput.focus()} 
    style={{ display: 'block', cursor: 'text' }} 
    > 
    <Input 
     error={this.props.error} 
     disabled={this.props.disabled} 
     inputRef={(input) => { this.textInput = input; }} 
    /> 
    </FormControl> 
.. 
0

を。私はmaterial-uiに非常に精通していないよ

constructor(props) { 
    super(props); 
    this.setFocus = this.setFocus.bind(this); 
} 
setFocus() { 
    this.textInput.focus(); 
} 
render() { 
    return(
    <FormControl 
     onClick={this.setFocus} 
     style={{ display: 'block', cursor: 'text' }} 
    > 
     <Input 
     error={this.props.error} 
     disabled={this.props.disabled} 
     ref={(input) => { this.textInput = input; }} 
     /> 
    </FormControl> 
); 
} 
関連する問題