【问题标题】:When calling super() in custom view, make sure to pass up the same props that your component's constructor was passed在自定义视图中调用 super() 时,确保传递与组件的构造函数相同的 props
【发布时间】:2018-05-07 00:43:54
【问题描述】:

这是我产生的代码

警告:LoaderView(...): 当在LoaderView 中调用 super() 时,使 确保传递与组件的构造函数相同的道具 通过了。

import * as React from "react";
import {ActivityIndicator, Text, View} from 'react-native'

    export class LoaderView extends React.Component {

        constructor(props) {
            super(props)
        }

        props = {
            title: "",
            loading: false
        }


        render() {
            if (this.props.loading) {
                return <View {...this.props} style={{flex: 1, justifyContent: 'center'}}>
                    <ActivityIndicator
                        size={"large"}
                        animating={true}/>

                    <Text
                        style={{textAlign: 'center', fontSize: 20, fontWeight: '500'}}>
                        {this.props.title}
                    </Text>
                </View>
            } else {
                return <View {...this.props} style={{flex: 1, justifyContent: 'center'}}>
                    <Text
                        style={{textAlign: 'center', fontSize: 20, fontWeight: '500'}}>
                        {this.props.title}
                    </Text>
                </View>
            }
        }

    }

如何解决上述代码中的这个警告?

【问题讨论】:

  • 尝试静态 defaultProps = { title: "", loading: false };而不是 props = { ... }

标签: javascript reactjs react-native ecmascript-6


【解决方案1】:

我刚刚使用了this.props = props,这对我有用!

constructor(props) {
    super(props)
    this.props = props
}

【讨论】:

    【解决方案2】:

    我收到了这个警告,结果证明这对我来说是一个红鲱鱼。请注意,尽管有此警告,但代码仍然有效。 解决方案是为您的 props 对象声明一个接口,并确保您不会错过任何属性。特别是,您可能缺少 id。就我而言,不需要构造函数,super(props) 也无济于事。示例:

    export interface LoaderProps extends React.Props<LoaderProps> {
      id: string;
      title: string;
      loading: bool;
    }
    
    export class LoaderView extends React.Component<LoaderProps> {
      //...
    }
    

    【讨论】:

      【解决方案3】:

      使用 defaultProps 代替 props

      static defaultProps = {
          title: "",
          loading: false
      }
      

      【讨论】:

      • defaultProps 会起作用,而不是 props 有什么具体原因吗?
      • @RahulRastogi 如果传递给构造函数的道具与类中定义的道具不同,则隐含的是“this.props”。
      • 它对我不起作用。我应该这样做:constructor(props) { super(props); [...] }
      猜你喜欢
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 2016-11-26
      • 1970-01-01
      • 2012-05-22
      • 2012-12-06
      相关资源
      最近更新 更多