【问题标题】:Why does this.props.onLayout not exist for my React Native component?为什么我的 React Native 组件不存在 this.props.onLayout?
【发布时间】:2019-10-29 15:04:36
【问题描述】:

我的 React Native 应用程序中有以下类(使用 Typescript):

class Component1 extends React.Component<IntroProps, {}> {
  constructor(props){
    super(props)
    console.log(props.onLayout)
  }
  ...
}

我在View 类的文档中读到,任何View 或从它继承的组件都具有this.props.onLayout。但是,这会记录undefined,如果我使用this.props.onLayout 而不是props.onLayout,它会给出警告“属性'onLayout' 在'Readonly & Readonly' 类型上不存在”。 我见过其他人在他们的组件中使用this.props.onLayout 的例子与我的类似,除了我使用 TypeScript。

我想知道的:

为什么我无法在此处访问this.props.onLayout,如何访问?

【问题讨论】:

    标签: javascript reactjs typescript react-native


    【解决方案1】:

    onlayout属于视图,可以使用如下代码:

    class Component1 extends React.Component<IntroProps, {}> {
      constructor(props){
        super(props)
      }
      render() {
       <View onLayout={this.props.onLayout} style={[{},this.props.containStyle]}>
          <Image source={{ uri: 'http://fillmurray.com/200/200' }} width={200} 
         height={200} />
          <Text>My Picture</Text>
        </View>
      }
      ...
    } 
    class Example extends Component {
      //this is a method
      onLayout = (e) => {
        this.setState({
          width: e.nativeEvent.layout.width,
          height: e.nativeEvent.layout.height,
          x: e.nativeEvent.layout.x,
          y: e.nativeEvent.layout.y
        })
      }
    
      render (
        <Component1  onLayout={this.onLayout} containerStyle={width:this.state.width}/>
      )
    }
    

    你可以看看这个article,在一些内容中,它展示了 React.componet 源代码并对其进行了分析。实际上,React.component 是一个函数。

    function ReactComponent(props, context, updater) {
      this.props = props;
      this.context = context;
      this.refs = emptyObject;
      // We initialize the default updater but the real one gets injected by the
      // renderer.
      this.updater = updater || ReactNoopUpdateQueue;
    }
    

    想学的越多,可以看文章,看源码。

    【讨论】:

    • 是的,我看过这段代码。问题是我的 render() 方法中最外层的组件不是 ,因此您引用的 onLayout 方法不存在。知道我能做些什么吗?将整个内容包装在 View 中也不起作用。
    • 我更新答案,Text,TextInput这样的基本视图也有onLayout,React.Component主要控制LiftCycle,组成有视图的组件。
    猜你喜欢
    • 2017-05-21
    • 2021-06-07
    • 2015-12-15
    • 1970-01-01
    • 2018-05-20
    • 2020-10-13
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多