加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:47:58 所属栏目:百科 来源:网络整理
导读:我正在尝试从不同的组件访问React Native组件的方法.它通过道具传递.不幸的是,似乎组件没有公开提供他们的方法.我怎样才能访问该方法? 看看下面的内容,你会看到InsideView有this.props.myModal,这是一个ShowMyModal组件.但是,它无法访问.openModal()方法. '
我正在尝试从不同的组件访问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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读