2016-11-17 52 views
1

上採用擴展操作時,這是我的成分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> 
     ); 
    }; 

我有2個styleprops補償。 A,第二個styleprop完全覆蓋第一個。

將特定樣式添加到第二個GenericTextInput的正確方法是什麼?

回答

5

我通常解構命名的屬性(style)出來的對象,並將剩餘的操作員可以收集剩下的道具到一個新的對象:

const {style, ...rest} = props; 

return (
    <TextInput 
    style={[styles.input, style]} 
    {...rest} 
    /> 
) 

請注意,這需要transform-object-rest-spread巴貝爾插件。這個插件包含在React Native Babel預設中,所以它可以直接使用 - 但是在沒有這個插件的其他JavaScript環境中可能無法使用。

+0

謝謝!我不知道這樣的解構是可能的:{foo,... bar} = obj – Edgar

+1

@Edgar我爲這個後代增加了一些關於這個語法的更多細節。 – jevakallio

0

如果你希望你的自定義樣式完全覆蓋預設的,我相信你可以這樣做

風格= {props.style || styles.input}

但我想你問如何讓自定義樣式覆蓋一些預設的樣式。在這種情況下,將

風格= {[styles.input,props.style]}

因爲你傳遞的財產下來,「風格」而不是「風格」你只是在下降的S結束。