在本机UIView中呈现JS组件时,OnPress不起作用

时间:2016-08-25 04:12:22

标签: react-native

场景是:

JS - > Objective-C - > JS

通常,我想在本机UIView中嵌入JS组件,JS视图应该响应用户交互事件,例如onPress事件。

详细说明: 在我的JS组件中,我调用了IOS本机方法,如下所示:

var CategoryManager = NativeModules.CategoryManager;
CategoryManager.showCategoryPopup();

在showCategoryPopup()objective-c方法中,我创建一个uiview,并将子视图添加到父uiview,子视图是使用RCTRootView类从JS组件创建的:

UIView *parentView = [UIView new];
RCTRootView *subview_1 = [[RCTRootView alloc] initWithBridge:[[RCCManager sharedIntance] getBridge] moduleName:@"CategoryViewPopup" initialProperties:nil];
[parentView addSubview: subview_1];

这里CategoryViewPopup是一个JS组件:

export default class CategoryViewPopup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      textToggle: false,
    };
  }

  render() {
    return (
      <TouchableOpacity onPress={this.toggleText.bind(this)}>
        <View style={{width: 100, height: 100, backgroundColor: 'red'}}>
          <Text>{this.state.textToggle ? "Text 1" : "Text 2"}</Text>
        </View>
      </TouchableOpacity>
    );
  }

  toggleText() {
    this.setState({
      textToggle: !this.state.textToggle,
    });
  }
}

onPress事件不起作用。

谢谢!

1 个答案:

答案 0 :(得分:0)

export default class CategoryViewPopup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      textToggle: false,
    };
  }

  render() {
    return (
      <View style = {styles.container}>
      <TouchableOpacity onPress={this.toggleText.bind(this)}>
        <View style={{width: 100, height: 100, backgroundColor: 'red'}}>
          <Text>{this.state.textToggle ? "Text 1" : "Text 2"}</Text>
        </View>
      </TouchableOpacity>
      </View>
    );
  }

  toggleText() {
    this.setState({
      textToggle: !this.state.textToggle,
    });
  }
}

const styles = StyleSheet.create({
  container : {
    flex : 1,
    backgroundColor : 'rgba(244,244,244,0.9)',
    justifyContent : 'center',
    alignItems : 'center'
  }
});
相关问题