[英]Why props is not working with my child component React JS (react native)
[英]Why does this.props.onLayout not exist for my React Native component?
我的 React Native 应用程序(使用 Typescript)中有以下 class:
class Component1 extends React.Component<IntroProps, {}> {
constructor(props){
super(props)
console.log(props.onLayout)
}
...
}
我在View
class 的文档中读到,从它继承的任何View
或组件都具有this.props.onLayout
。 但是,这会记录undefined
,如果我使用this.props.onLayout
而不是props.onLayout
,它会给出警告“Property 'onLayout' does not exist on type 'Readonly & Readonly<{ children?: ReactNode;>'”。 我已经看到其他人在他们的组件中使用this.props.onLayout
的例子类似于我的,除了我的使用 TypeScript。
我想知道的:
为什么这里访问this.props.onLayout
,怎么访问呢?
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}/>
)
}
你可以看看这篇文章,在一些内容中,它展示了 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;
}
想学的越多,可以看文章看源码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.