我是新来的本地人。我正在尝试从子类的父级调用函数。例如:我正在创建一个带有按钮的应用程序,当您按下它时,它将带您进入另一个页面。在另一页上,有一个按钮可以返回到主应用程序。
在此处输入代码
import React, { Component } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
export default class Parent extends Component {
constructor(props) {
super(props);
this.state = {showForm: false}
this.toggleForm = this.toggleForm.bind(this)
}
toggleForm = () => {
this.setState(prevState => ({showForm:!prevState.showForm}))}
render() {
if (this.state.showForm) return <Test />
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone!
Save to get a shareable url.
</Text>
<Button onPress={this.toggleForm} title='test'/>
</View>
);
}
}
export class Child extends Component {
constructor(props) {
super(props);
handleReturn = () => {
this.props.toggleForm()
}
render() {
return (
<View style={{padding: 150}}>
<Text> Hello World</Text>
<Button onPress={this.props.toggleForm} title='return'/>
</View>
)
}
}
}
感谢您的帮助!
在父组件中,您需要像这样渲染子组件:
render() {
if (this.state.showForm) return <Test />
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone!
Save to get a shareable url.
</Text>
<Button onPress={this.toggleForm} title='test'/>
** <Child click={this.doSomething}/> **
</View>
);
}
在子组件中:
export class Child extends Component {
constructor(props) {
super(props);
handleReturn = () => {
this.props.toggleForm()
}
render() {
return (
<View style={{padding: 150}}>
<Text> Hello World</Text>
** <Button onPress={this.props.click} title='return'/> **
</View>
)
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句