2017-08-07 191 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,你的选择给了我我需要的东西,谢谢 –