我实际上正在使用反应导航https://reactnavigation.org/,我有一个带有方法的组件:
class Sing extends Component {
singASong = () => {
console.log('hello i am singing');
}
}
此组件将用react-navigation和自定义header呈现,问题是:如何从自定义标题中调用方法singASong
?:
const routeStackNavigation = {
SingingMode: {
screen: Sing,
navigationOptions: ({ navigation }) => ({
header: (
<CustomNav onPressAction={() =>{
// how to call the method singASong from here ?
}
}
/>
),
}),
},
};
UPDATE
我以此设置并测试了值:
this.props.navigation.setParams({'onPress': 'akumen' });
setTimeout(() => {
console.log(this.props.navigation.getParam('onPress')); // akumen
}, 2000);
我用以下方法测试值:
onPress={() =>{
console.log('NAVIGATION',navigation);
console.log('ON PRESS',navigation.getParam('onPress'));
console.log('PARAMS',navigation.state.params);
return navigation.getParam('onPress');
}
}
但未定义
您可以使用导航参数:
在componentDidMount中
this.props.navigation.setParams({onPressAction: ()=>this.singASong()})
在navigationOptions中
<CustomNav onPressAction={navigation.getParam("onPressAction") }/>