La renderització condicional a React Native permet mostrar o ocultar components basant-se en certes condicions. Això és molt útil per crear interfícies d'usuari dinàmiques que responen a l'estat de l'aplicació o a les accions de l'usuari.
Conceptes clau
-
Operadors condicionals:
if/else- Operador ternari (
condició ? expr1 : expr2) - Operador lògic
&&
-
Renderització basada en l'estat:
- Utilitzar l'estat del component per determinar què renderitzar.
-
Renderització basada en props:
- Utilitzar les propietats passades als components per determinar què renderitzar.
Exemples pràctics
- Utilitzant
if/else
if/elseimport React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
class ConditionalRenderingExample extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
};
}
toggleLogin = () => {
this.setState({ isLoggedIn: !this.state.isLoggedIn });
};
render() {
let message;
if (this.state.isLoggedIn) {
message = <Text>Welcome back!</Text>;
} else {
message = <Text>Please log in.</Text>;
}
return (
<View>
{message}
<Button title="Toggle Login" onPress={this.toggleLogin} />
</View>
);
}
}
export default ConditionalRenderingExample;
- Utilitzant l'operador ternari
import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
class TernaryOperatorExample extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
};
}
toggleLogin = () => {
this.setState({ isLoggedIn: !this.state.isLoggedIn });
};
render() {
return (
<View>
{this.state.isLoggedIn ? (
<Text>Welcome back!</Text>
) : (
<Text>Please log in.</Text>
)}
<Button title="Toggle Login" onPress={this.toggleLogin} />
</View>
);
}
}
export default TernaryOperatorExample;
- Utilitzant l'operador lògic
&&
&&import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
class LogicalAndOperatorExample extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
};
}
toggleLogin = () => {
this.setState({ isLoggedIn: !this.state.isLoggedIn });
};
render() {
return (
<View>
{this.state.isLoggedIn && <Text>Welcome back!</Text>}
{!this.state.isLoggedIn && <Text>Please log in.</Text>}
<Button title="Toggle Login" onPress={this.toggleLogin} />
</View>
);
}
}
export default LogicalAndOperatorExample;Exercicis pràctics
Exercici 1: Renderització condicional amb if/else
Crea un component que mostri un missatge diferent segons si l'usuari ha completat o no una tasca.
Solució
import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
class TaskCompletionExample extends Component {
constructor(props) {
super(props);
this.state = {
isTaskCompleted: false,
};
}
toggleTaskCompletion = () => {
this.setState({ isTaskCompleted: !this.state.isTaskCompleted });
};
render() {
let message;
if (this.state.isTaskCompleted) {
message = <Text>Task completed!</Text>;
} else {
message = <Text>Task not completed.</Text>;
}
return (
<View>
{message}
<Button title="Toggle Task Completion" onPress={this.toggleTaskCompletion} />
</View>
);
}
}
export default TaskCompletionExample;Exercici 2: Renderització condicional amb l'operador ternari
Crea un component que mostri un missatge diferent segons si l'usuari ha activat o no una funció.
Solució
import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
class FeatureToggleExample extends Component {
constructor(props) {
super(props);
this.state = {
isFeatureEnabled: false,
};
}
toggleFeature = () => {
this.setState({ isFeatureEnabled: !this.state.isFeatureEnabled });
};
render() {
return (
<View>
{this.state.isFeatureEnabled ? (
<Text>Feature is enabled!</Text>
) : (
<Text>Feature is disabled.</Text>
)}
<Button title="Toggle Feature" onPress={this.toggleFeature} />
</View>
);
}
}
export default FeatureToggleExample;Exercici 3: Renderització condicional amb l'operador lògic &&
Crea un component que mostri un missatge diferent segons si l'usuari ha activat o no les notificacions.
Solució
import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
class NotificationToggleExample extends Component {
constructor(props) {
super(props);
this.state = {
areNotificationsEnabled: false,
};
}
toggleNotifications = () => {
this.setState({ areNotificationsEnabled: !this.state.areNotificationsEnabled });
};
render() {
return (
<View>
{this.state.areNotificationsEnabled && <Text>Notifications are enabled!</Text>}
{!this.state.areNotificationsEnabled && <Text>Notifications are disabled.</Text>}
<Button title="Toggle Notifications" onPress={this.toggleNotifications} />
</View>
);
}
}
export default NotificationToggleExample;Resum
La renderització condicional és una tècnica essencial en React Native per crear interfícies d'usuari dinàmiques i responsives. Hem vist com utilitzar if/else, l'operador ternari i l'operador lògic && per controlar què es mostra a la pantalla basant-se en l'estat o les propietats del component. Practicar aquests conceptes amb exercicis pràctics t'ajudarà a dominar la renderització condicional en les teves aplicacions React Native.
