[英]React Native pass function to child component as prop
我是React Native(和React)的新手,我正在嘗試將一個函數作為prop傳遞給一個組件。
我的目標是創建一個組件,其組件的實例化器可以設置其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的道具包含該功能,但它不存在。
當寫handlePress={this.handlePress.bind(this)}
你傳遞一個語句執行(當執行時,如果執行則返回一個函數)。 預期的是通過handlePress={this.handlePress}
(並在構造函數中進行綁定)或handlePress={() => this.handlePress()}
傳遞函數本身,它傳遞一個匿名函數,該函數在執行時將在this
上下文中執行handlePress。
// Parent
handleClick( name ){
alert(name);
}
<Child func={this.handleClick.bind(this)} />
// Children
let { func } = this.props;
func( 'VARIABLE' );
使用箭頭功能無需關心綁定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> ); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.