javascript - 设置 React Native 子组件

标签 javascript reactjs react-native

我尝试通过 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/

相关文章:

javascript - 如何匹配 URL 但不在括号中

node.js - 创建 React App 时 package.json 中缺少依赖项

IE 中的 JavaScript 运行时错误 : Unable to get property 'top'

javascript - 如何去除 javascript 中的 json 注释

javascript - EmberJS : The best way to reload controller's model based on another property?

reactjs - setCount(prev => prev + 1) 和 setCount(count + 1) 有什么区别?

javascript - 如何在 React v6 中重定向

ios - React Native 0.61 : With autolinking, 还需要在 Podfile 中添加行吗?

react-native - 如何使用 rn-fetch-blob 在 react-native 中上传文件?

react-native - React Native 元素搜索栏边框线未清除