我是React Native(和React)的新手,我试图将一个函数作为道具传递给一个组件。
我的目标是创建一个组件,其组件的实例化器可以设置其onPress功能,以便它更具可重用性。
到目前为止,这是我的代码。
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
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的道具能够包含这个功能,但它并不存在。
答案 0 :(得分:2)
写handlePress={this.handlePress.bind(this)}
时,你传递一个语句执行(当执行时,如果执行则返回一个函数)。期望的是通过handlePress={this.handlePress}
传递函数本身(并在构造函数中进行绑定)或传递匿名函数的handlePress={() => this.handlePress()}
,该函数在执行时将在this
类上下文中执行handlePress
答案 1 :(得分:2)
// Parent
handleClick( name ){
alert(name);
}
<Child func={this.handleClick.bind(this)} />
// Children
let { func } = this.props;
func( 'VARIABLE' );
答案 2 :(得分:2)
使用arrow function无需绑定this
。
我建议在调用props方法之前检查null。
App.js
export default class App extends Component<Props> {
constructor () {
super();
}
handlePress = () => {
// Do what you want.
}
render () {
return (
<View>
<TouchableButton onPress={this.handlePress}/>
</View>
);
}
}
TouchableButton.js
import React, { Component } from 'react';
import { TouchableHighlight } from 'react-native';
import AppButton from "./app-button";
export default class TouchableButton extends Component {
constructor(props){
super(props);
}
handlePress = () => {
// Need to check to prevent null exception.
this.props.onPress?.(); // Same as this.props.onPress && this.props.onPress();
}
render () {
return (
<TouchableHighlight onPress={this.handlePress}>
<AppButton/>
</TouchableHighlight>
);
}
}