我有两个类Parent类和Child类,我想从Parent类调用Child类函数。问题是我想从父标题按钮调用子类函数。我尝试了refs
方法,但没有得到结果。还有其他方法吗?
子类:
class FilterSlider extends React.Component {
constructor(props) {
super(props);
console.log(props);
}
PanelShow = () => {
this._panel.show();
};
render() {
return (
<SlidingUpPanel
ref={(c) => (this._panel = c)}
draggableRange={{ top: height / 1.2, bottom: -10 }}
animatedValue={this._draggedValue}
showBackdrop={false}
>
<View style={styles.panel}>
<View style={styles.panelHeader}>
<Text style={{ color: '#FFF' }}>Bottom Sheet Peek</Text>
</View>
<View style={styles.container}>
<Text>Bottom Sheet Content</Text>
</View>
</View>
</SlidingUpPanel>
);
}
}
export default FilterSlider;
和父类:
class ReportsListView extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.navigation.setParams({
openSlider : this._openSlider
});
}
_openSlider() {
this.refs.child.PaenlShow();
}
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
title : navigation.state.params.name,
headerLeft : null,
headerStyle : {
backgroundColor : '#4c8572'
},
headerRight : (
<View style={{ paddingLeft: 10, flexDirection: 'row' }}>
<TouchableOpacity onPress={() => params.openSlider()}> //from this icon i want to call the child PanelShow function.
<Icon name="arrow-left" size={30} color="#ffffff" />
</TouchableOpacity>
</View>
),
headerTitleStyle : {
flex : 1,
color : '#fff',
alignItems : 'center',
justifyContent : 'center',
fontWeight : 'bold'
}
};
render()
{
return(
<FilterSlider ref = 'child'/>
)
}
};
答案 0 :(得分:0)
您错误地使用了ref
属性。要解决此问题,您可以尝试以下操作:
父项
class ReportsListView extends Component {
componentWillMount(){
this.refs.child = null;
}
render() {
return (
<FilterSlider ref={(ref) => {
this.refs.child = ref
}}/>
)
}
}
现在,您可以从子组件中调用函数,例如:this.refs.child.doSomethings()
。