将原生传递函数作为子元素反应给子组件 [英] React Native pass function to child component as prop
问题描述
我是React Native(和React)的新手,我正试图将功能作为道具传递给组件.
I'm new to React Native (and React), and I'm trying to pass a function as a prop to a component.
我的目标是创建一个组件,该组件的实例化程序可以设置其onPress功能,从而使其更可重用.
My goal is to create a component where its onPress functionality can be set by the instantiator of the component, so that it is more reusable.
到目前为止,这是我的代码.
Here is my code so far.
App.js
import React, { Component } from 'react';
import { View } from 'react-native';
import TouchableButton from './components/touchable-button';
export default class App extends Component<Props> {
constructor () {
super();
}
handlePress () {
// this should be called when my custom component is clicked
}
render () {
return (
<View>
<TouchableButton handlePress={this.handlePress.bind(this)}/>
</View>
);
}
}
TouchableButton.js
TouchableButton.js
import React, { Component } from 'react';
import { TouchableHighlight } from 'react-native';
import AppButton from "./app-button";
export default class TouchableButton extends Component {
handlePress;
constructor(props){
super(props);
}
render () {
return (
<TouchableHighlight onPress={
this.props.handlePress
}>
<AppButton/>
</TouchableHighlight>
);
}
}
我将handlePress函数作为prop handlePress传递.我希望TouchableButton的道具包含该功能,但是它不存在.
I am passing the handlePress function as the prop handlePress. I would expect the TouchableButton's props to contain that function, however it isn't there.
推荐答案
编写 handlePress = {this.handlePress.bind(this)}
时,您传递了一条语句执行程序(执行该语句的时间和条件会返回功能).期望的是通过 handlePress = {this.handlePress}
(并在构造函数中进行绑定)或 handlePress = {()=>传递函数本身.this.handlePress()}
传递了一个匿名函数,该函数在执行时将在 this
类上下文中执行handlePress.
When writing handlePress={this.handlePress.bind(this)}
you passing a statement execution ( which when and if executed returns a function). What is expected is to pass the function itself either with handlePress={this.handlePress}
(and do the binding in the constructor) or handlePress={() => this.handlePress()}
which passes an anonymous function which when executed will execute handlePress in this
class context.
这篇关于将原生传递函数作为子元素反应给子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!