这是我的组件 A:
const GenericTextInput = (props) => {
return (
<TextInput
style={styles.input}
{...props}
/>
);
};
这是我的组件 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>
);
};
我想向我的组件 B 中的第二个 GenericTextInput
添加特定的样式。在组件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>
);
};
我将在 comp 中使用 2 个 style
props
。 A,第二个 style
prop
将完全覆盖第一个。
向第二个 GenericTextInput
添加特定样式的正确方法是什么?
最佳答案
我通常解构对象的命名属性 (style
),然后使用 rest 运算符将剩余的 props 收集到一个新对象中:
const {style, ...rest} = props;
return (
<TextInput
style={[styles.input, style]}
{...rest}
/>
)
请注意,这需要 transform-object-rest-spread巴贝尔插件。此插件包含在 React Native Babel 预设中,因此它可以开箱即用——但在没有此插件的情况下可能无法在其他 JavaScript 环境中使用。
关于javascript - 在子组件上使用展开运算符时 React Native : what is a proper way to pass style as props,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40665370/