我尝试通过 React Native 中的父组件向子组件发送数据。
Parent Component
<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
我有错误。我该如何解决这个问题并正确设置?
最佳答案
我认为最好的方法是使用对象扩展运算符:
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
}
};
您像 const 一样定义样式,因此会出现错误。你也可以通过let将其定义为变量。
关于javascript - 设置 React Native 子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45554780/