将函数从HOC传递到组件(React, React native)

Pass function from HOC to component (React, React native)

本文关键字:React native 组件 函数 HOC      更新时间:2023-09-26

我是一个关于facebook ReactJS和React-native的初学者,所以我在教程的帮助下开始编码如何在Android和iOS之间共享代码。

本教程稍后将实现一个按钮,用于切换状态。不幸的是,这是用mixin制作的。我想用一个hoc组件来做。

原始mixin

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;
我的

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>
            )
        }
    }