React Native:当在子组件上使用spread运算符时,将样式作为props传递的正确方法是什么

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环境中使用.


Mat*_*Aft 5

如果您希望自定义样式完全覆盖预设样式,我相信您可以执行以下操作

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 即可。