我要调用子组件函数,该子组件函数是通过app.js文件中的for循环创建的。
这是我的app.js;
import React, { Component } from 'react';
import { View, Button } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
const fields = [];
for (let i = 0; i < assets.fieldNames[assets.systemLang].length; i++) {
fields.push(
<InfoField
key={i}
title={assets.fieldNames[assets.systemLang][i]}
value="" />
);
};
this.state = {
fields,
};
}
callFunctionFromInfoField = (id) => {
const fields = [...this.state.fields];
fields[id].showAlert(); /// ** I NEED SOMETHING LIKE THIS **
}
render() {
return (
<View>
<View>
{
this.state.fields
}
</View>
<Button onPress={this.callFunctionFromInfoField(2)} />
</View>
);
}
}
这是我的孩子部分;
import React, { Component } from 'react';
import { Text, TouchableOpacity,Animated } from 'react-native';
export default class InfoField extends Component {
constructor(props) {
super(props);
this.state = {
};
}
showAlert = () => {
alert(`${this.props.title} is empty. Please fill it`);
}
render() {
return (
<Animated.View style={styles.container}>
<TouchableOpacity style={{ justifyContent: "center" }}>
<Text style={styles.text} {...this.props}> {this.props.title} </Text>
</TouchableOpacity>
</Animated.View>
);
}
}
首先,我需要从数组中获取子组件 ,然后在其中调用showAlert函数。 有这样的蚂蚁方法吗?
fields [1] .showAlert();