React Native TouchableHighlight:获取组件和上下文

时间:2016-07-12 17:56:25

标签: react-native

我希望在TouchableHighlight中的onPress上获取组件中的两个道具,并获取全局此上下文。

我可以单独使用:

 onPress={this.alertProp} // get props from TouchableHighlight using this.myProp

onPress={() => this.alertProp()} // get global this to use e.g. this.state

获得两者的简单方法?

2 个答案:

答案 0 :(得分:1)

如果您需要从子组件获取道具,则可以使用ref。 E.g:



class Example extends React.Component {

  alertProp(index) {
    //now "this" has your global component,
    //and this._touchables[index] is the ref
    //of your TouchableHighlight
  }

  render() {
    const data = [1, 2, 3, 4];
    return (
     <View>
      {data.map((item, index) => {
       return (
         <TouchableHighlight
          onPress={() => this.alertProp.bind(this)(index)}
          ref={(t) => this._touchables[index] = t}
         />;
        );
      }}
    </View>
   );
    
  }
}
&#13;
&#13;
&#13;

如果我正确理解了您的问题,这会让您的alertProp函数访问全局(组件)状态和您的子TouchableHighlight组件的道具。

答案 1 :(得分:0)

最后,通过绑定更多参数,我能够使其发挥作用。

class Example extends React.Component {



alertProp(param1, param2) {
    //now "this" has your global component,
    //param1, param2 don't get rewrited if they are dynamic inside a loop
  }

  render() {
    const data = [1, 2, 3, 4];
    var param1;
    return (
     <View>
      {data.map((item, index) => {
       param1 = index;
       return (
         <TouchableHighlight
          onPress={this.alertProp.bind(this,param1, param2)}
         />;
        );
      }}
    </View>
   );

  }
}