【问题标题】:...attributes in react-native function component...属性在 react-native 功能组件中
【发布时间】:2021-01-08 06:57:46
【问题描述】:

我在 react-native 应用程序中有以下功能组件。在第二行代码中,...attributes 令人困惑。虽然我知道它代表较新 JavaScript 版本中的扩展语法,但我找不到 attributes 的含义。如果它说..props,那是可以理解的。我尝试谷歌但找不到任何合适的答案。

问题

下面第二行代码sn-p中的attrributes是什么意思?

  const Loader = (props) => {
  const { loading, loaderColor, loaderText, ...attributes } = props;

  return (
    <Modal
      transparent={true}
      animationType={'none'}
      visible={loading}
      onRequestClose={() => {
        console.log('close modal');
      }}>
      <View style={styles.modalBackground}>
        <View style={styles.activityIndicatorWrapper}>
          <ActivityIndicator
            animating={loading}
            color={loaderColor? loaderColor : '#0000ff'}
            size={Platform.OS === 'ios' ? 'large' : 75}
          />
          {loaderText ? (
            <View style={{ flexDirection: 'row' }}>
              <Text style={styles.modalText}>{loaderText}</Text>
            </View>
          ) : (
            ''
          )}
        </View>
      </View>
    </Modal>
  );
};

【问题讨论】:

  • 代码从哪里来??
  • 这是我在 react native 应用中看到的一个组件。

标签: javascript react-native spread-syntax


【解决方案1】:

attributes 是新创建的常量的名称,其中包含来自props 的其余属性。

const {
  a,
  b,
  ...objectContainingEveryOtherPropertyExceptAB
} = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};
console.log(objectContainingEveryOtherPropertyExceptAB);

所以如果你像这样使用&lt;Loader loading foo="bar" /&gt; 的组件,那么attributes 将等于{ foo: 'bar' }

【讨论】:

  • 很好的答案。谢谢。所以..attributes 意味着属性常量将包含除以下属性之外的所有内容:loading、loaderColor、loaderText。很酷的构造。回到 ocd sn-p 中的组件,我认为 ...attributes 在上面的代码中并不是真正需要的,因为它没有在 Loader 组件中使用。使用以下代码行使用对象解构来设置加载、loaderColor、loaderText 就足够了:{loading, loaderColor, loaderText} = props;
  • 一个与您的&lt;Loader loading foo="bar" /&gt; 示例相关的问题,其中未设置加载属性。它会自动设置为 undefined 还是 null?
猜你喜欢
  • 2020-01-02
  • 2021-06-14
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 2022-01-14
  • 2019-12-15
  • 2017-10-02
相关资源
最近更新 更多