반응 네이티브에서 컴포넌트 숨기기 / 보이기
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/hideCancel
.
또한 처음부터 단추를 숨기려면 어떻게해야합니까?
나는 이런 식으로 할 것입니다 :
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()}
);
}
});
렌더 기능에서 :
{ this.state.showTheThing &&
<TextInput/>
}
그런 다음 수행하십시오.
this.setState({showTheThing: true}) // to show it
this.setState({showTheThing: false}) // to hide it
기본적으로 반응 또는 반응에서 구성 요소 숨기기 / 표시 또는 추가 / 제거가 Android 또는 iOS에서 작동하지 않습니다. 우리 대부분은 비슷한 전략이있을 것이라고 생각합니다
View.hide = true or parentView.addSubView(childView)
그러나 기본 작업에 반응하는 방식은 완전히 다릅니다. 이러한 종류의 기능을 달성하는 유일한 방법은 컴포넌트를 DOM에 포함 시키거나 DOM에서 제거하는 것입니다.
이 예제에서는 버튼 클릭을 기준으로 텍스트보기의 가시성을 설정합니다.
이 작업의 기본 개념은 버튼 클릭 이벤트가 발생하면 값이 토글 될 때 초기 값이 false로 설정된 state라는 상태 변수를 작성하는 것입니다. 이제 컴포넌트 생성 중에이 상태 변수를 사용할 것입니다.
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>
);
}
}
이 스 니펫에서 주목해야 할 것은 renderIf
실제로 전달 된 부울 값을 기반으로 전달 된 컴포넌트를 리턴하는 함수입니다.
renderIf(predicate)(element)
renderif.js
'use strict';
const isFunction = input => typeof input === 'function';
export default predicate => elemOrThunk =>
predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;
render ()에서 JSX를 조건부로 표시하거나 다음과 같이 null을 반환 할 수 있습니다.
render(){
return({yourCondition ? <yourComponent /> : null});
}
두 이미지 사이를 전환해야했습니다. 그들 사이의 조건부 전환으로 이미지가 표시되지 않고 5 초 지연되었습니다.
downvoted amos answer의 접근법을 사용하고 있습니다. 올바른 형식으로 코드를 주석에 넣기가 어렵 기 때문에 새로운 답변으로 게시.
렌더 기능 :
<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>
스타일 :
var styles = StyleSheet.create({
logo: {
width: 200,
height: 200,
},
hidden: {
width: 0,
height: 0,
},
});
대부분의 경우 나는 이런 식으로 일하고 있습니다 :
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>
);
}
}
프로그래밍에 익숙하지 않다면이 줄은 이상해야합니다.
{this.state.isHidden ? <ToHideAndShowComponent/> : null}
이 줄은
if (this.state.isHidden)
{
return ( <ToHideAndShowComponent/> );
}
else
{
return null;
}
그러나 JSX 컨텐츠에 if / else 조건 (예 : 렌더링 함수의 return () 부분)을 작성할 수 없으므로이 표기법을 사용해야합니다.
이 작은 트릭은 많은 경우에 매우 유용 할 수 있으며 조건을 빠르게 확인할 수 있기 때문에 개발에 사용하는 것이 좋습니다.
문안 인사,
부모보기 숨기기 및 표시Activity Indicator
constructor(props) {
super(props)
this.state = {
isHidden: false
}
}
다음 과 같이 숨기기 및 표시
{
this.state.isHidden ? <View style={style.activityContainer} hide={false}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
}
전체 참조
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 버튼은 다음과 같이 설정된 상태를 누름
onSignupPress() {
this.setState({isHidden: true})
}
숨겨야 할 때
this.setState({isHidden: false})
그냥 사용
style={ width:0, height:0 } // to hide
React Native의 레이아웃에는 display
CSS와 유사한 속성 지원이 있습니다. 가능한 값 : none
및 flex
(기본값). https://facebook.github.io/react-native/docs/layout-props#display
<View style={{display: 'none'}}> </View>
뷰를 표시 / 숨기기하려는 동일한 문제가 있었지만 실제로 항목을 추가 / 제거하거나 다시 렌더링 할 때 UI가 점프하는 것을 원하지 않았습니다.
나는 그것을 처리하기 위해 간단한 구성 요소를 썼다. 기본적으로 애니메이션되지만 전환하기 쉽습니다. 추가 정보와 함께 GitHub 및 NPM 에 넣었 지만 모든 코드는 다음과 같습니다.
npm install --save react-native-hideable-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;
추가 옵션은 스타일링을 통해 절대 위치를 적용 하여 숨겨진 구성 요소를 화면 외부 좌표로 설정하는 것입니다.
<TextInput
onFocus={this.showCancel()}
onChangeText={(text) => this.doSearch({input: text})}
style={this.state.hide ? {position: 'absolute', top: -200} : {}}
/>
이전 제안 중 일부와 달리, 이것은 구성 요소를 뷰에서 숨기지 만 뷰를 렌더링하여 (DOM에 유지) 진정으로 보이지 않게 합니다.
내 모듈 react-native-display 를 사용하여 구성 요소를 표시하거나 숨길 수 있습니다.
컴포넌트가로드되어 있어야하지만 숨겨져 있어야한다면 불투명도를 0으로 설정할 수 있습니다. (예를 들어 엑스포 카메라에 필요했습니다)
//in constructor
this.state = {opacity: 100}
/in component
style = {{opacity: this.state.opacity}}
//when you want to hide
this.setState({opacity: 0})
아주 쉽게. 아래처럼 () => this.showCancel ()로 변경하십시오.
<TextInput
onFocus={() => this.showCancel() }
onChangeText={(text) => this.doSearch({input: text})} />
<TouchableHighlight
onPress={this.hideCancel()}>
<View>
<Text style={styles.cancelButtonText}>Cancel</Text>
</View>
</TouchableHighlight>
버튼을 숨기거나 보려면 아래 방법을 사용하고 있습니다. 그것이 당신을 도울 것입니다 바랍니다. 상태를 업데이트하고 숨기기 CSS를 추가하면 충분합니다.
constructor(props) {
super(props);
this.state = {
visibleStatus: false
};
}
updateStatusOfVisibility () {
this.setStatus({
visibleStatus: true
});
}
hideCancel() {
this.setStatus({visibleStatus: false});
}
render(){
return(
<View>
<TextInput
onFocus={this.showCancel()}
onChangeText={(text) => {this.doSearch({input: text}); this.updateStatusOfVisibility()}} />
<TouchableHighlight style={this.state.visibleStatus ? null : { display: "none" }}
onPress={this.hideCancel()}>
<View>
<Text style={styles.cancelButtonText}>Cancel</Text>
</View>
</TouchableHighlight>
</View>)
}
실제로, iOS 개발에서 react-native
내가 사용할 때 display: 'none'
또는 아래와 같은 것 :
const styles = StyleSheet.create({
disappearImage: {
width: 0,
height: 0
}
});
iOS는 Image 구성 요소 onLoad
등을 로드하지 않으므로 다음과 같은 것을 사용하기로 결정했습니다.
const styles = StyleSheet.create({
disappearImage: {
width: 1,
height: 1,
position: 'absolute',
top: -9000,
opacity: 0
}
});
유일한 방법은 표시하거나 네이티브 같은 응용 프로그램 상태의 매개 변수의 값을 확인한다 반응의 구성 요소를 숨기 state
거나 props
. 다음과 같이 완전한 예를 제공했습니다.
import React, {Component} from 'react';
import {View,Text,TextInput,TouchableHighlight} from 'react-native'
class App extends Component {
constructor(props){
super(props);
this.state={
show:false
}
}
showCancel=()=>{
this.setState({show:true})
};
hideCancel=()=>{
this.setState({show:false})
};
renderTouchableHighlight(){
if(this.state.show){
return(
<TouchableHighlight
style={{borderColor:'black',borderWidth:1,marginTop:20}}
onPress={this.hideCancel}>
<View>
<Text>Cancel</Text>
</View>
</TouchableHighlight>
)
}
return null;
}
render() {
return (
<View style={{justifyContent:'center',alignItems:'center',flex:1}}>
<TextInput
style={{borderColor:'black',borderBottomWidth:1}}
onFocus={this.showCancel}
/>
{this.renderTouchableHighlight()}
</View>
);
}
}
export default App;
참고 URL : https://stackoverflow.com/questions/30266831/hide-show-components-in-react-native
'IT박스' 카테고리의 다른 글
jQuery $ .getScript () 메소드를 사용하여 여러 JS 파일을 포함하는 방법 (0) | 2020.07.16 |
---|---|
구분 된 문자열을 List로 split ()하는 방법 (0) | 2020.07.16 |
URL에 대한 PHP 유효성 검사 / 정규식 (0) | 2020.07.16 |
AngularJS로 배열을 필터링하고 필터링 된 객체의 속성을 ng-model 속성으로 사용하려면 어떻게합니까? (0) | 2020.07.16 |
Android에서 EditText의 최대 문자 수를 어떻게 설정합니까? (0) | 2020.07.16 |