gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:18:16 26 4
gpt4 key购买 nike

我正在尝试从不同的组件访问 React Native 组件的方法。它是通过 props 传递的。不幸的是,这些组件似乎没有公开提供它们的方法。我如何才能访问该方法?

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

enter image description here

'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,
ActionSheetIOS,
StyleSheet,
Text,
TouchableOpacity,
View,
} = 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);

关于react-native - 在 React Native 中,如何从另一个组件访问一个组件的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31998091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com