gpt4 book ai didi

javascript - 在子组件上使用展开运算符时 React Native : what is a proper way to pass style as props,

转载 作者:搜寻专家 更新时间:2023-11-01 04:49:54 24 4
gpt4 key购买 nike

这是我的组件 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com