Javascript 在本机反应中隐藏/显示组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30266831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hide/Show components in react native
提问by Crysfel
I'm really new to React Native and I'm wondering how can I hide/show a component.
Here's my test case:
我真的是 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>
I have a TextInputcomponent, what I want is to show the TouchableHighlightwhen the input gets the focus, then hide the TouchableHighlightwhen the the user press the cancel button.
我有一个TextInput组件,我想要的是TouchableHighlight在输入获得焦点时显示,然后TouchableHighlight在用户按下取消按钮时隐藏。
I don′t know how to "access" the TouchableHighlightcomponent in order to hide/show it inside of my functions showCancel/hideCancel.
Also, how can I hide the button from the very beginning?
我不知道如何“访问”TouchableHighlight组件以在我的函数中隐藏/显示它showCancel/hideCancel。
另外,如何从一开始就隐藏按钮?
采纳答案by Mayank Patel
I would do something like this:
我会做这样的事情:
var myComponent = React.createComponent({
getInitialState: function () {
return {
showCancel: false,
};
},
toggleCancel: function () {
this.setState({
showCancel: !this.state.showCancel
});
}
_renderCancel: function () {
if (this.state.showCancel) {
return (
<TouchableHighlight
onPress={this.toggleCancel()}>
<View>
<Text style={styles.cancelButtonText}>Cancel</Text>
</View>
</TouchableHighlight>
);
} else {
return null;
}
},
render: function () {
return (
<TextInput
onFocus={this.toggleCancel()}
onChangeText={(text) => this.doSearch({input: text})} />
{this._renderCancel()}
);
}
});
回答by Krishan Gupta
In your render function:
在您的渲染功能中:
{ this.state.showTheThing &&
<TextInput/>
}
Then just do:
然后就这样做:
this.setState({showTheThing: true}) // to show it
this.setState({showTheThing: false}) // to hide it
回答by Rajan Twanabashu
In react or react native the way component hide/show or add/remove does not work like in android or iOS. Most of us think there would be the similar strategy like
在 react 或 react native 中,组件隐藏/显示或添加/删除的方式不像在 android 或 iOS 中那样工作。我们大多数人认为会有类似的策略
View.hide = true or parentView.addSubView(childView)
But the way react native work is completely different. The only way to achieve this kind of functionality is to include your component in your DOM or remove from DOM.
但是对原生工作的反应方式是完全不同的。实现这种功能的唯一方法是将您的组件包含在 DOM 中或从 DOM 中删除。
Here in this example I am going set the visibility of text view based on the button click.
在这个例子中,我将根据按钮点击设置文本视图的可见性。
The idea behind this task is the create a state variable called state having the initial value set to false when the button click event happens then it value toggles. Now we will use this state variable during the creation of component.
这个任务背后的想法是创建一个名为 state 的状态变量,当按钮点击事件发生时,它的初始值设置为 false 然后它的值切换。现在我们将在组件的创建过程中使用这个状态变量。
import renderIf from './renderIf'
class FetchSample extends Component {
constructor(){
super();
this.state ={
status:false
}
}
toggleStatus(){
this.setState({
status:!this.state.status
});
console.log('toggle button handler: '+ this.state.status);
}
render() {
return (
<View style={styles.container}>
{renderIf(this.state.status)(
<Text style={styles.welcome}>
I am dynamic text View
</Text>
)}
<TouchableHighlight onPress={()=>this.toggleStatus()}>
<Text>
touchme
</Text>
</TouchableHighlight>
</View>
);
}
}
the only one thing to notice in this snippet is renderIfwhich is actually a function which will return the component passed to it based on the boolean value passed to it.
在这个片段中唯一需要注意的是renderIf,它实际上是一个函数,它将根据传递给它的布尔值返回传递给它的组件。
renderIf(predicate)(element)
renderif.js
渲染器
'use strict';
const isFunction = input => typeof input === 'function';
export default predicate => elemOrThunk =>
predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;
回答by Mar
in render() you can conditionally show the JSX or return null as in:
在 render() 中,您可以有条件地显示 JSX 或返回 null,如下所示:
render(){
return({yourCondition ? <yourComponent /> : null});
}
回答by mauron85
I needed to switch between two images. With conditional switching between them there was 5sec delay with no image displayed.
我需要在两个图像之间切换。在它们之间有条件切换时,有 5 秒的延迟,没有图像显示。
I'm using approach from downvoted amos answer. Posting as new answer because it's hard to put code into comment with proper formatting.
我正在使用来自被低估的 amos 答案的方法。发布为新答案,因为很难以正确的格式将代码放入评论中。
Render function:
渲染功能:
<View style={styles.logoWrapper}>
<Image
style={[styles.logo, loading ? styles.hidden : {}]}
source={require('./logo.png')} />
<Image
style={[styles.logo, loading ? {} : styles.hidden]}
source={require('./logo_spin.gif')} />
</View>
Styles:
款式:
var styles = StyleSheet.create({
logo: {
width: 200,
height: 200,
},
hidden: {
width: 0,
height: 0,
},
});
回答by KuroAku
Most of the time i'm doing something like this :
大多数时候我都在做这样的事情:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {isHidden: false};
this.onPress = this.onPress.bind(this);
}
onPress() {
this.setState({isHidden: !this.state.isHidden})
}
render() {
return (
<View style={styles.myStyle}>
{this.state.isHidden ? <ToHideAndShowComponent/> : null}
<Button title={this.state.isHidden ? "SHOW" : "HIDE"} onPress={this.onPress} />
</View>
);
}
}
If you're kind of new to programming, this line must be strange to you :
如果您是编程新手,那么您一定很陌生:
{this.state.isHidden ? <ToHideAndShowComponent/> : null}
This line is equivalent to
这条线相当于
if (this.state.isHidden)
{
return ( <ToHideAndShowComponent/> );
}
else
{
return null;
}
But you can't write an if/else condition in JSX content (e.g. the return() part of a render function) so you'll have to use this notation.
但是您不能在 JSX 内容中编写 if/else 条件(例如渲染函数的 return() 部分),因此您必须使用此表示法。
This little trick can be very useful in many cases and I suggest you to use it in your developments because you can quickly check a condition.
这个小技巧在很多情况下都非常有用,我建议您在开发中使用它,因为您可以快速检查条件。
Regards,
问候,
回答by Harshal Valanda
HideAnd Showparent view of Activity Indicator
隐藏和显示父视图Activity Indicator
constructor(props) {
super(props)
this.state = {
isHidden: false
}
}
Hideand Showas Follow
隐藏和显示为关注
{
this.state.isHidden ? <View style={style.activityContainer} hide={false}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
}
Full reference
完整参考
render() {
return (
<View style={style.mainViewStyle}>
<View style={style.signinStyle}>
<TextField placeholder='First Name' keyboardType='default' onChangeFirstName={(text) => this.setState({firstName: text.text})}/>
<TextField placeholder='Last Name' keyboardType='default' onChangeFirstName={(text) => this.setState({lastName: text.text})}/>
<TextField placeholder='Email' keyboardType='email-address' onChangeFirstName={(text) => this.setState({email: text.text})}/>
<TextField placeholder='Phone Number' keyboardType='phone-pad' onChangeFirstName={(text) => this.setState({phone: text.text})}/>
<TextField placeholder='Password' secureTextEntry={true} keyboardType='default' onChangeFirstName={(text) => this.setState({password: text.text})}/>
<Button style={AppStyleSheet.buttonStyle} title='Sign up' onPress={() => this.onSignupPress()} color='red' backgroundColor='black'/>
</View>
{
this.state.isHidden ? <View style={style.activityContainer}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
}
</View>
);
}
On Button presss set state as follow
On 按钮按下设置状态如下
onSignupPress() {
this.setState({isHidden: true})
}
When you need to hide
当你需要隐藏
this.setState({isHidden: false})
回答by Estev?o Lucas
React Native's layout has the displayproperty support, similar to CSS.
Possible values: noneand flex(default).
https://facebook.github.io/react-native/docs/layout-props#display
React Native 的布局有display属性支持,类似于 CSS。可能的值:none和flex(默认)。
https://facebook.github.io/react-native/docs/layout-props#display
<View style={{display: 'none'}}> </View>
回答by amos
just use
只是使用
style={ width:0, height:0 } // to hide
回答by Shivo'ham 0
constructor(props) {
super(props);
this.state = {
visible: true,
}
}
declare visible false so by default modal / view are hide
声明可见假所以默认模式/视图是隐藏的
example = () => {
示例 = () => {
this.setState({ visible: !this.state.visible })
}
}
**Function call **
**函数调用**
{this.state.visible == false ?
<View>
<TouchableOpacity
onPress= {() => this.example()}> // call function
<Text>
show view
</Text>
</TouchableOpacity>
</View>
:
<View>
<TouchableOpacity
onPress= {() => this.example()}>
<Text>
hide view
</Text>
</TouchableOpacity>
</View>
}


