Edg*_*gar 4 javascript react-native
这是我的组件A:
const GenericTextInput = (props) => {
return (
<TextInput
style={styles.input}
{...props}
/>
);
};
Run Code Online (Sandbox Code Playgroud)
这是我的组件B:
const SignIn = (props) => {
return (
<View>
<GenericTextInput
placeholder="Email"
autoFocus={true}
keyboardType="email-address"
returnKeyType="next"
autoCorrect={false}
placeholderTextColor='rgba(250,248,244, .4)'
underlineColorAndroid='rgba(250,248,244, .7)'
/>
<GenericTextInput
placeholder="Password"
placeholderTextColor='rgba(250,248,244, .4)'
underlineColorAndroid='rgba(250,248,244, .7)'
secureTextEntry={true}
/>
</View>
);
};
Run Code Online (Sandbox Code Playgroud)
我想GenericTextInput在我的组件B中为第二个添加特定样式.在组件A中我想使用spread operator(它非常方便).
如果我只是做:
//component A
const GenericTextInput = (props) => {
return (
<TextInput
style={[styles.input, props.styles]}
{...props}
/>
);
};
//component B
const SignIn = (props) => {
return (
<View>
<GenericTextInput
placeholder="Email"
autoFocus={true}
keyboardType="email-address"
returnKeyType="next"
autoCorrect={false}
placeholderTextColor='rgba(250,248,244, .4)'
underlineColorAndroid='rgba(250,248,244, .7)'
/>
<GenericTextInput
placeholder="Password"
placeholderTextColor='rgba(250,248,244, .4)'
underlineColorAndroid='rgba(250,248,244, .7)'
secureTextEntry={true}
style={styles.customStyleForSecondInput}
/>
</View>
);
};
Run Code Online (Sandbox Code Playgroud)
我有2个style props在可比.A,第二个style prop将完全覆盖第一个.
为第二个添加特定样式的正确方法是GenericTextInput什么?
jev*_*lio 13
我通常style为对象解析命名的property(),并使用rest运算符将剩余的props收集到一个新对象中:
const {style, ...rest} = props;
return (
<TextInput
style={[styles.input, style]}
{...rest}
/>
)
Run Code Online (Sandbox Code Playgroud)
请注意,这需要transform-object-rest-spread Babel插件.此插件包含在React Native Babel预设中,因此它可以开箱即用 - 但如果没有此插件,可能无法在其他JavaScript环境中使用.
如果您希望自定义样式完全覆盖预设样式,我相信您可以执行以下操作
style={props.style || styles.input}
Run Code Online (Sandbox Code Playgroud)
但我认为您问的是如何让自定义样式覆盖一些预设样式。在那种情况下就会是
style={[styles.input, props.style]}
Run Code Online (Sandbox Code Playgroud)
因为您将属性作为“style”而不是“styles”传递,所以您只需在末尾删除 s 即可。
| 归档时间: |
|
| 查看次数: |
11217 次 |
| 最近记录: |