我对React Native真的很陌生,我想知道如何隐藏/显示组件。
下面是我的测试用例:
<TextInput
onFocus={this.showCancel()}
onChangeText={(text) => this.doSearch({input: text})} />
<TouchableHighlight
onPress={this.hideCancel()}>
<View>
<Text style={styles.cancelButtonText}>Cancel</Text>
</View>
</TouchableHighlight>
我有一个TextInput组件,我想要的是在输入得到焦点时显示TouchableHighlight,然后在用户按下取消按钮时隐藏TouchableHighlight。
我不知道如何“访问”TouchableHighlight组件,以便隐藏/显示它在我的函数showCancel/ hideccancel中。
此外,我如何从一开始就隐藏按钮?
我也有同样的问题,我想要显示/隐藏视图,但我真的不希望UI在添加/删除东西或必须处理重新渲染时跳来跳去。
我写了一个简单的组件来处理它。默认为动画,但易于切换。我把它放在GitHub和NPM上,但所有的代码都在下面。
NPM install——save react-native- hidden -view
import React, { Component, PropTypes } from 'react';
import { Animated } from 'react-native';
class HideableView extends Component {
constructor(props) {
super(props);
this.state = {
opacity: new Animated.Value(this.props.visible ? 1 : 0)
}
}
animate(show) {
const duration = this.props.duration ? parseInt(this.props.duration) : 500;
Animated.timing(
this.state.opacity, {
toValue: show ? 1 : 0,
duration: !this.props.noAnimation ? duration : 0
}
).start();
}
shouldComponentUpdate(nextProps) {
return this.props.visible !== nextProps.visible;
}
componentWillUpdate(nextProps, nextState) {
if (this.props.visible !== nextProps.visible) {
this.animate(nextProps.visible);
}
}
render() {
if (this.props.removeWhenHidden) {
return (this.visible && this.props.children);
}
return (
<Animated.View style={{opacity: this.state.opacity}}>
{this.props.children}
</Animated.View>
)
}
}
HideableView.propTypes = {
visible: PropTypes.bool.isRequired,
duration: PropTypes.number,
removeWhenHidden: PropTypes.bool,
noAnimation: PropTypes.bool
}
export default HideableView;