例如,当您拥有表单组件时,如何使用导航栏中的按钮提交组件状态的一部分?
const navBtn = (iconName,onPress) => ( <TouchableOpacity onPress={onPress} style={styles.iconWrapper} > <Icon name={iconName} size={cs.iconSize} style={styles.icon} /> </TouchableOpacity> ) class ComponentName extends Component { static navigationOptions = { header: (props) => ({ tintColor: 'white',style: { backgroundColor: cs.primaryColor },left: navBtn('clear',() => props.goBack()),right: navBtn('done',() => this.submitForm()),// error: this.submitForm is not a function }),title: 'Form',} constructor(props) { super(props); this.state = { formText: '' }; } submitForm() { this.props.submitFormAction(this.state.formText) } render() { return ( <View> ...form goes here </View> ); } }
使用setParams发送绑定函数,然后您将可以访问该函数中的组件状态.
例:
constructor(props) { super(props); this._handleButtonNext = this._handleButtonNext.bind(this); this.state = { selectedIndex: 0 } } componentDidMount() { this.props.navigation.setParams({ handleButtonNext: this._handleButtonNext,}); } _handleButtonNext() { let action = NavigationActions.setParams({ params: { selectedImage: images[this.state.selectedIndex] } }); this.props.navigation.dispatch(action); }
现在,您可以拥有与组件状态相关的按钮处理程序.
static navigationOptions = ({ navigation }) => { const { state,setParams,navigate } = navigation; const params = state.params || {}; return { headerTitleStyle: { alignSelf: 'center' },title: 'Select An Icon',headerRight: <Button title='Next' onPress={params.handleButtonNext} /> } }