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

时间:2016-10-19 10:44:52

标签: javascript android ios reactjs react-native

我是关于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只传递数据,而不是函数吗? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:6)

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