React Nativeでは、ビュー要素style
はキャメルケース付きオブジェクトでCSSプロパティ名を使用するプロパティを受け入れます。
const styleObj = {
width: 200,
marginTop: 10
}
要素は、次のようなスタイルオブジェクトの配列も受け入れます。
<MyComponent style={[ styleObj, styleProp && styleProp ]} />
共有ベースボタンインターフェイスに依存する抽象化されたボタンコンポーネントがいくつかあります。簡単にするために:
interface IButton {
style?: ViewStyle | ViewStyle[] // <-- ViewStyle is exported by react native, and contains all the allowed style properties for a View component
}
この定義で十分だと思いましたが、理解しにくい問題がいくつかあります。
をDropDown
レンダリングするコンポーネントがありますButton
。スタイルプロップを使用すると、エラーが発生します。
<Button
style={[
{
backgroundColor: backgroundColor || COLORS.lightRed,
borderRadius: 3,
height: 44,
width: '100%',
},
style && style, // <-- type is ViewStyle | ViewStyle[], this is passed in as a prop
]}
上記はエラーをスローします:
Type (ViewStyle | ViewStyle[] | undefined)[] is not assignable to ViewStyle | ViewStyle[] | undefined
スタイルをキャストした場合:style && (style as ViewStyle)
別のエラーが発生します:
Type (ViewStyle | undefined)[] is not assignable to ViewStyle[]
配列全体をキャストするとViewStyle
、エラーがクリアされます。
<Button
style={[
{
backgroundColor: backgroundColor || COLORS.lightRed,
borderRadius: 3,
height: 44,
width: '100%',
},
style && style,
] as ViewStyle}
これは問題ありませんが、少し混乱しています。私のコンポーネントは同じ小道具インターフェースを使用しているので、TypeScriptが混乱しているという予感があります。最終的に、これらのエラーが発生している理由と、キャストに依存する必要があるという私の定義の何が間違っているのかがわかりません。
当然のことながら、最善の解決策を見つけるのに少し時間がかかりました。
スタイルの小道具を入力するときはViewStyle
、TextStyle
(の代わりにStyleProp<T>
)などを使用し、スタイルの配列を渡すときはStylesheet.flatten()
、タイプの非互換性を消すために使用します。
<Button
style={Stylesheet.flatten([
{
backgroundColor: backgroundColor || COLORS.lightRed,
borderRadius: 3,
height: 44,
width: '100%',
},
style && style,
])}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加