在我的应用程序中,我在模块 xyz.js 中定义了一个默认类 A,它在导航堆栈上呈现页面。根据 A 类的状态变量之一,呈现的 View 会有所不同。例如,如果应用程序置于“编辑模式”,则除了应用程序不处于“编辑模式”时呈现的其他标准 View 之外,还会呈现编辑 View 。我不知道如何从不同的模块 abc.js 更改该状态变量并导致与实例化的类 A 关联的 View 重新渲染。在我的模块 abc.js 中,我创建了导航堆栈,并且有一个用于 touchableHighlight 按钮的 onPress 处理程序,用于将应用程序置于“编辑模式”。在该处理程序中,我尝试调用 A 类中的函数“Edit()”。但该函数似乎没有被调用。它可能与绑定(bind)有关,但这个概念并不是我完全理解的。
这是我所拥有的:
模块abc.js:
import XYZ from './xyz';
import {Edit} from './xyz';
import { pencilEditButton } from './Images';
const App = createStackNavigator(
{
Home: {
screen: My App,
navigationOptions: ({ navigation }) => ({
title: 'myApp',
headerRight: (
<View>
<TouchableHighlight
onPress={() => Edit()}
underlayColor="gray">
<View>
<Image source={pencilEditButton} style={styles.navigationButtonImage} />
</View>
</TouchableHighlight>
</View>
),
}),
},
}
);
export default createAppContainer(App);
模块 xyz.js:
export default class XYZ extends React.Component {
constructor(props) {
super(props);
this.state = {
editMode: false,
};
};
// Create a method to handle the press of the edit button on the navigation bar
Edit() {
console.log("editMode: ", editMode);
this.setstate({ editMode: true });
console.log("editMode: ", editMode);
alert('User wants to edit a mix!');
};
render() {
return (
<View style={styles.container}>
{ this.state.editMode === true ?
<TouchableHighlight
onPress={this._onXPressed}
underlayColor="white">
<View style={[styles.flowRight, styles.controlButton]}>
<Text style={styles.buttonText}>{'Edit Mode'}</Text>
</View>
</TouchableHighlight>
:
<TouchableHighlight
onPress={this._onYPressed}
underlayColor="white">
<View style={[styles.flowRight, styles.controlButton]}>
<Text style={styles.buttonText}>{'Non Edit Mode'}</Text>
</View>
</TouchableHighlight>
}
</View>
);
}
}
正如你所看到的,在模块 xyz.js 的类 XYZ 的构造函数后面有一个名为“Edit()”的函数。当按下编辑按钮时,从模块 abc.js 调用此函数。但是,当按下编辑按钮时,状态不会更新,警报 View 不会显示,并且 View 不会重新渲染。如何正确调用 Edit() 以便更新状态变量“editMode”并重新渲染 View ?
最佳答案
如果您想遵循您正在使用的模式,则需要将其处理在“我的应用程序”组件内,该组件会在堆栈导航器中渲染。您必须使用refs 通过以下代码示例了解如何调用 Edit 函数。
import XYZ from './xyz';
export default class MyApp extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: 'myApp',
headerRight: navigation.state.params && navigation.state.params.edit ? (
<View>
<TouchableHighlight
onPress={() => navigation.state.params.edit()}
underlayColor="gray"
>
<View>
<Image source={pencilEditButton} style={styles.navigationButtonImage} />
</View>
</TouchableHighlight>
</View>
) : null,
})
constructor(props) {
super(props);
this.onEdit = this.onEdit.bind(this);
}
componentDidMount() {
this.props.navigation.setParams({ edit: this.onEdit });
}
onEdit() {
if (this.xyz_Ref) {
this.xyz_Ref.Edit();
}
}
render() {
return (
<View>
<XYZ ref={ref => this.xyz_Ref = ref} />
</View>
);
}
}
关于javascript - 如何从不同的模块调用 React Native 类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55111830/