在React和React Native中传递组件之间的函数

时间:2016-03-16 15:45:50

标签: reactjs react-native

我正在尝试将我在ReactJS中启动的原型迁移到React Native。到目前为止很简单,直到我开始在包装组件上迁移上下文保持的函数。对于我的生活,我无法在定义函数的元素的上下文中调用它。

这是我正在努力实现的简化版本:

ReactJS

var Parent = React.createClass({
  childContextTypes: {
    onButtonClick: React.PropTypes.func
  },
  onButtonClick: function() {
    console.log("Button pressed", this); // this is instance of Parent when done in ReactJS
  },
  getChildContext: function() {
    return {
      onButtonClick: this.onButtonClick
    }
  },
  render: function() {
    return (<div><Child /></div>);
  }
});

var Child = React.createClass({
  contextTypes: {
    onButtonClick: React.PropTypes.func
  },
  render: function() {
    return (
      <button onClick={this.context.onButtonClick}>Click me</button>
    ); 
  }
});

React Native

class Parent extends Component {
  static childContextTypes = {
    onButtonClick: React.PropTypes.func
  };

  getChildContext() {
    return {
      onButtonClick: this.onButtonClick
    }
  };

  onButtonClick() {
    console.log("Button pressed", this); // this is returning `undefined`
  };

  render() {
    return (<div><Child /></div>);
  }
}

class Child extends Component {
  static contextTypes = {
    onButtonClick: React.PropTypes.func
  };

  render() {
    return (
      <TouchableHighlight onPress={() => this.context.onButtonClick()}>
        <Text>Click Me</Text>
      </TouchableHighlight>
    );
  }
}

道歉,如果上述内容不是100%准确(我现在只是手写,以解决问题)。我有信心问题是我在父组件上声明函数,或者在子组件的onPress事件中执行它。

另一方面,如果有更好的方法让按钮点击子组件影响更广泛的应用程序而不将事件传递给上面的父组件上的函数,那么我很想知道,它对我来说似乎有点混乱......

2 个答案:

答案 0 :(得分:0)

在问到这个问题的9个月里,有很多变化。

  1. 您不应使用上下文https://facebook.github.io/react/docs/context.html

  2. 传递Redux周围的动作是最流行的flex样式扩展,我建议使用它。 http://redux.js.org/

  3. 我建议使用纯组件,只要有内部状态(如果需要),并且没有函数作为组件之间的道具传递。

  4. 组件构成越来越受欢迎。

  5. 来自ReactJS上下文文档https://reactjs.org/docs/context.html#before-you-use-context

      

    如果你只想避免在一些级别上传递一些道具,那么组件组合通常比上下文更简单。

答案 1 :(得分:0)

只需添加.bind(this),您的功能将如下:

getChildContext: function() {
    return {
      onButtonClick: this.onButtonClick.bind(this)
    }
相关问题