我想在用户提交一些文本输入后关闭组件。在我关闭之前,我想要调用一些函数(基于提交的文本)。
我尝试将多个回调传递给onSubmitEditing道具。这不起作用,因为无法保证在卸载组件之前我的所有功能都已完成。
所以我想知道为什么允许这样做?
我最终编写了一个退出函数,它在卸载promise之前包装了我必须做的所有事情。这是这种情况的最佳做法吗?
class AlbumCreateView extends Component {
constructor(props){
super(props)
this.state = {
newAlbumName: '',
}
this._keyboardDidHide = this._keyboardDidHide.bind(this)
this._keyboardWillShow = this._keyboardWillShow.bind(this)
this.exitFunction = this.exitFunction.bind(this)
}
componentWillMount () {
this.keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
}
componentWillUnmount (e) {
this.keyboardWillShowListener.remove();
this.keyboardDidHideListener.remove();
LayoutAnimation.configureNext(LayoutAnimation.Presets.linear)
this.props.raiseKeyboard(0)
}
_keyboardWillShow (e) {
LayoutAnimation.configureNext(LayoutAnimation.Presets.linear)
this.props.raiseKeyboard(e.endCoordinates.height)
}
_keyboardDidHide () {
}
newAlbumSaveHandler() {
MySwiftClass.createAndSaveToNewAlbum(this.state.newAlbumName)
LayoutAnimation.configureNext(LayoutAnimation.Presets.linear),
this.props.raiseKeyboard(0)
}
exitFunction() { *****
const saveAndDismissKeyboardPromise = new Promise((resolve, reject) => {
//I want to make sure these these two functions are called before the component unmounts
this.newAlbumSaveHandler()
Keyboard.dismiss()
resolve()
})
//this component lives in a modal, the following callback toggles the isVisible state in the parent and unmounts this component
saveAndDismissKeyboardPromise.then(this.props.toggleModal)
}
render(){
return(
<View style={styles.flatList}>
<View style={styles.albumButton}>
</View>
<TextInput onSubmitEditing={this.exitFunction} *****
keyboardType='default'
autoFocus={true}
autoCorrect={false}
textAlign='center'
onChangeText={(newAlbumName) => this.setState({newAlbumName})}
enablesReturnKeyAutomatically={true}
style={{width: 200}}
/>
</View>
)
}
}