2017-08-07 108 views
0

我試圖通過從父組件向道具中的道具發送數據給React Native中的子項。 Parent Component設置React Native子組件

<Card> 
 
    <CardSection> 
 
    <Input 
 
     proportion={5} 
 
     label="Email" 
 
    /> 
 
    </CardSection> 
 
    <CardSection> 
 
    <Input 
 
     proportion={3} 
 
     label="Password" 
 
    /> 
 
    </CardSection> 
 
</Card>

Children Component

const Input = ({ proportion, label }) => { 
 
    const { inputStyle } = styles; 
 
    inputStyle.flex = proportion; 
 

 
    return (
 
    <View style={containerStyle}> 
 
     <Text>{label}</Text> 
 
     <TextInput style={inputStyle} /> 
 
    </View> 
 
); 
 
}; 
 

 
const style = { 
 
    inputStyle: { 
 
    flex: 2 
 
    } 
 
};

而且我有錯誤You attempted set the key 'flex' with the value '3' on an object that is meant to be immutable and has been frozen。有趣的事實,當我有一個<Input /> Component一切正常,並設置flex: 5,我達到了我想要的,但第二個<Input /> Component我有錯誤。我如何解決這個問題並設置正確?

回答

3

我想好的辦法是使用對象蔓延運營商:

const Input = ({ proportion, label }) => { 
    const { inputStyle } = styles; 

    return (
    <View style={containerStyle}> 
     <Text>{label}</Text> 
     <TextInput style={{...inputStyle, flex: proportion}} /> 
    </View> 
); 
}; 

const style = { 
    inputStyle: { 
    flex: 2 
    } 
}; 

你這樣定義常量的風格,讓你得到一個錯誤。你也可以通過let將它定義爲變量。

+1

在RN中的另一種方式是'style = {[inputStyle,{flex:proportion}]}' – madox2

+0

@ madox2,你的選擇給了我我需要的東西,謝謝 –