[英]Pass function from HOC to component (React, React native)
我是關於Facebook ReactJS和React-native的初學者,所以我在教程的幫助下開始編寫代碼 ,展示了如何在Android和iOS之間共享代碼 。
本教程后面會實現一個按鈕,用於切換狀態。 不幸的是,這是用mixin制作的。 我想用HOC組件來做。
原創混音
export default {
getInitialState() {
return {
pressed: false
}
},
handlePress() {
this.setState({pressed: !this.state.pressed});
}
}
以上mixin的原始電話
{ ...
render() {
const buttonStyle = [styles.button];
if (this.state.pressed) buttonStyle.push(styles.buttonPress);
return (
<TouchableOpacity onPress={this.handlePress.bind(this)} style={buttonStyle}>
<Text style={styles.text}>{this.props.text}</Text>
</TouchableOpacity>
)
}
}
reactMixin.onClass(Button, ButtonCommon);
export default Button;
我的HOC
export var ButtonComp = (ComposedComponent) => class extends Component {
constructor(props) {
super(props);
this.state = {pressed: false};
}
handlePress() {
this.setState({pressed: !this.state.pressed});
}
render() {
return <ComposedComponent {...this.props} data={this.state.pressed} />;
}
};
我的HOC用法
import { ButtonComp } from './button.common';
class Button extends Component {
render() {
const buttonStyle = [styles.button];
if (this.props.data) buttonStyle.push(styles.buttonPress);
return (
<TouchableOpacity onPress={this.handlePress.bind(this)} style={buttonStyle}>
<Text style={styles.text}>{this.props.text}</Text>
</TouchableOpacity>
)
}
}
export default ButtonComp(Button); // Enhanced component
當我執行上面的代碼時,我得到以下錯誤(當調用this.handle時,所以在TouchableOpacity標記中):
undefined不是對象(評估'this.handlePress.bind')
那么我做錯了什么? HOC只傳遞數據,而不是函數嗎? 謝謝您的幫助!
HOC不能那樣做。 但是,如果您希望通過this
方法調用包裝組件中可用的HOC函數,則必須通過props
傳遞它:
export var ButtonComp = (ComposedComponent) => class extends Component {
constructor(props) {
super(props);
this.state = {pressed: false};
this.handlePress = this.handlePress.bind(this);
}
handlePress() {
this.setState({pressed: !this.state.pressed});
}
render() {
return <ComposedComponent {...this.props} handlePress={this.handlePress} data={this.state.pressed} />;
}
};
class Button extends Component {
render() {
const buttonStyle = [styles.button];
if (this.pressed) buttonStyle.push(styles.buttonPress);
return (
<TouchableOpacity onPress={this.props.handlePress} style={buttonStyle}>
<Text style={styles.text}>{this.props.text}</Text>
</TouchableOpacity>
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.