将函数从HOC传递到组件(React, React native)
Pass function from HOC to component (React, React native)
我是一个关于facebook ReactJS和React-native的初学者,所以我在教程的帮助下开始编码如何在Android和iOS之间共享代码。
本教程稍后将实现一个按钮,用于切换状态。不幸的是,这是用mixin制作的。我想用一个hoc组件来做。
原始mixinexport 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;
我的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。处理发生,所以在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>
)
}
}
相关文章:
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- 使用Jest测试React Native应用程序
- 是否存在React Native“;WEB代码安全防护”;
- React Native Listview留有余地
- 如何在React Native中绘制图形
- 在iOS和Android上使用React native时,我还能使用本机第三方lirbraries吗
- 使用createContainer将Meteor数据获取到React Native中时出现问题
- React Native当前是否支持访问用户'的通讯簿
- React Native-What'It’在任何地方都要留下逗号
- React Native DeviceEventEmitter键盘WillShow停止工作
- 与React Native的Chart.js等效
- 如何使用webview在React Native中使用Highcharts
- 如何在React Native的MapView中设置标记
- React Native NavigatorIOS
- 如何获得React Native TextInput以在提交后保持焦点
- 使用react native检测应用程序终止
- 可以在React Native中制作一个自哈希应用程序
- React Native AlertOS api中可能有多个文本字段
- react native中常见的js模块
- 在React Native+Redux中使用Navigator