react-native – 在React Native中,如何从另一个组件访问一个组件的方法?

前端之家收集整理的这篇文章主要介绍了react-native – 在React Native中,如何从另一个组件访问一个组件的方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从不同的组件访问React Native组件的方法.它通过道具传递.不幸的是,似乎组件没有公开提供他们的方法.我怎样才能访问该方法

看看下面的内容,你会看到InsideView有this.props.myModal,这是一个ShowMyModal组件.但是,它无法访问.openModal()方法.

'use strict';

var React = require('react-native');
var {
  AppRegistry,ActionSheetIOS,StyleSheet,Text,View,} = React;

var InsideView = React.createClass({
  makeItOpen: function() {
    debugger;
    this.props.myModal.openModal();
  },render: function() {
    return (
      <View>
        <Text onPress={() => this.makeItOpen()}>Click me!</Text>
      </View>
    );
  }
});

var ShowMyModal = React.createClass({
  getInitialState: function() {
    return {
      isModalOpen: false,}
  },openModal() {
    this.setState({isModalOpen: true});
  },closeModal() {
    this.setState({isModalOpen: false});
  },render: function() {
    return (
      <Text>isModalOpen = {String(this.state.isModalOpen)}</Text>
    );
  }
});

var AwesomeProject = React.createClass({
  getInitialState: function() {
    return {
      myModal: <ShowMyModal />,render: function() {
    return (
      <View style={{padding: 30}}>
        <InsideView myModal={this.state.myModal}/>
        {this.state.myModal}
      </View>
    );
  },});

AppRegistry.registerComponent('AwesomeProject',() => AwesomeProject);
像这样的东西应该工作:
'use strict';

var React = require('react-native');
var {
  AppRegistry,TouchableOpacity,} = React;

var InsideView = React.createClass({
  render: function() {
    return (
      <View>
        <TouchableOpacity onPress={() => this.props.openModal()}><Text>Open modal!</Text></TouchableOpacity>
        <TouchableOpacity onPress={() => this.props.closeModal()}><Text>Close modal!</Text></TouchableOpacity>
      </View>
    );
  }
});

var ShowMyModal = React.createClass({
  render: function() {
    return (
      <Text>isModalOpen = {String(this.props.isVisible)}</Text>
    );
  }
});

var SampleApp = React.createClass({
  getInitialState: function() {
    return {
      isModalOpen: false
    }
  },_openModal: function() {
    this.setState({
      isModalOpen: true
    });
  },_closeModal() {
    this.setState({
      isModalOpen: false
    });
  },render: function() {
    return (
      <View style={{padding: 30}}>
        <InsideView openModal={this._openModal} closeModal={this._closeModal}/>
        <ShowMyModal isVisible={this.state.isModalOpen}/>
      </View>
    );
  },});

AppRegistry.registerComponent('SampleApp',() => SampleApp);
原文链接:https://www.f2er.com/react/300989.html

猜你在找的React相关文章