2017-08-03 4 views
2

ネイティブに反応する新しいです。私はエラーがあるときTextInputのスタイリングを変更しようとしています。リアクションネイティブスタイリング(条件付き)

私のコードを醜いものにすることはできますか?

<TextInput 
     style={touched && invalid? 
     {height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, borderWidth: 2, borderColor: 'red'} : 
     {height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10}} 
</TextInput> 

答えて

4

使用StyleSheet.createこのため、スタイル構図を行うには、

テキスト有効なテキスト、および無効なテキストのスタイルを作ります。

const styles = StyleSheet.create({ 
    text: { 
     height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, 
    }, 
    textvalid: { 
     borderWidth: 2, 
    }, 
    textinvalid: { 
     borderColor: 'red', 
    }, 
}); 

これらのスタイルをスタイルの配列とともにグループ化します。

<TextInput 
    style={[styles.text, touched && invalid ? styles.invalid : styles.valid]} 
</TextInput> 

アレイスタイルの場合、後者のものは前のものにマージされ、同じキーの上書きルールが適用されます。 、

<TextInput style={getTextStyle(this.state.touched, this.state.invalid)}></TextInput> 

を次に、あなたのクラスコンポーネントの外に書く::

+0

これはよさそうだ、ありがとう! –

0

は、次のようにコードを更新し

getTextStyle(touched, invalid) { 
if(touched && invalid) { 
    return { 
    height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, borderWidth: 2, borderColor: 'red' 
    } 
} else { 
    return { 
     height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10 
    } 
} 
}