7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[ React Native ]要素がfocusされたらstyleを変更する

Posted at

はじめに

もともと、webアプリの勉強をしており、htmlやcss、Reactなどのフレームワークを勉強していましたが、Reactを勉強したついでに、React Nativeも勉強してみました。
React Nativeを始めてみて、スタイルを当てるということに対して、webアプリとかなり違うなぁと戸惑いました。
その一つとして、タイトルの通り、要素がfocusされたらstyleを変更することを紹介したいと思います。

開発環境は、Expoで構築し、デザインは、NativeBaseを用いています。

環境

"expo": "^33.0.0",
"native-base": "^2.12.1",
"react": "16.8.3",

Inputをかく

NativeBaseを用いて、まずは、フォームを作ります。

App.js
import {Item, Input} from 'native-base';

<Item rounded style={{borderColor: '#ddd'}}>
    <Input placeholder='e.g.)  hoge' />
</Item>

これで、以下のようになります。
IMG_0539.jpg

focus時にデザインを変更する

React Nativeでは、cssほどデザインの自由度もなく、また、擬似クラスなどもありません。そのため、webアプリではcssで簡単に実装していたfocusも、javascriptによって制御する必要があります。

今回は、フォーカスすると、フォームの線の色が変更するコンポーネントを作りたいと思います。

App.js
import {Item, Input} from 'native-base';

<Item rounded style={{borderColor: '#ddd'}}>
    <Input 
        placeholder='e.g.)  hoge'
        onFocus={this.onFocus}        ++追加
        onBlur={this.onBlur} />    ++追</Item>

onFocusもonBlurも、セットで使われるイベント属性で、onFocusは、フォーカスが要素に与えられる時に発生します。また、onBlurは、その要素からフォーカスが外れた時に発生します。

そして、それぞれで呼び出している関数は、以下の通りです。

App.js
//stateの部分のみ切り取り
this.state = {borderColor: '#666'}

onFocus = () => {
    this.setState({
        borderColor: 'skyblue',
    })
}
onBlur = () => {
    this.setState({
        borderColor: '#666',
    })
}

onFocus関数では、フォーカス時に指定したい色を指定し、onBlur関数では、フォーカスが外れた時の色をしていています。また、stateの初期値では、フォーカスもブラーも発生しない状態の初期の色を指定しています。

それでは、stateの変更により、Inputのボーダーの色も変更するようにしていきます。

App.js
import {Item, Input} from 'native-base';

<Item rounded style={{borderColor: this.state.borderColor}}>    //変更
    <Input 
        placeholder='e.g.)  hoge'
        onFocus={this.onFocus}        
        onBlur={this.onBlur} />
</Item>

動画は用意していませんが、フォーカスすると、右の画像になります。
IMG_0539.jpg
IMG_0540.jpg

終わりに

cssで書いていた時はサクッとしていたことがネイティブではできないことが多いので、一つ一つ調べて勉強していきたいと思います。

7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?