我是 Facebook 的 ReactJS 和 React-native 的初学者,所以我在教程的帮助下开始编码,展示 how to share code between Android and 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>
)
}
}
关于javascript - 将函数从 HOC 传递到组件(React、React native),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40129169/