- Hands-On Design Patterns with React Native
- Mateusz Grzesiukiewicz
- 296字
- 2021-08-13 15:12:58
JSX standard tricks
Before we proceed further, I want to show you the best practices when it comes to writing your JSX markup. This will make your journey through my further examples much easier.
Let's start with the simple rules:
- If there are no children within your component, use a self-closing tag:
// good
<Button onPress={handlePress} />
// bad
<Button onPress={handlePress}></Button>
- If you need to display a component based on some condition, then use the && operator:
// bad
function HelloComponent(props) {
if (isSomeCondition) {
return <p>Hello!</p>;
}
return null;
}
// bad
const HelloComponent = () => { return isSomeCondition ? <p>Hello!</p> : null };
// ok (probably it will require some logic before return)
const HelloComponent = () => { return isSomeCondition && <p>Hello!</p> };
// almost good (isSomeCondition can be passed using props)
const HelloComponent = () => isSomeCondition && <p>Hello!</p>;
// best: use above solution but within encapsulating component
// this way HelloComponent is not tightly tied to isSomeCondition
const HelloComponent = () => <p>Hello!</p>;
const SomeComponent = () => (
// <== here some component JSX ...
isSomeCondition && <HelloComponent />
// <== the rest of encapsulating component markup here
);
The preceding practices only apply if the other option is null. If the false case is also a component, you can use the b ? x : y operator or even a simple if-else approach, however, it should comply with your project's best practices.
- If you use the b ? x : y operator, then you may find that curly braces ({}) come in handy:
const SomeComponent = (props) => (
<View>
<Text>{props.isLoggedIn ? 'Log In' : 'Log Out'}</Text>
</View>
);
- You can also use curly braces ({}) to destructure props objects:
const SomeComponent = ({ isLoggedIn, ...otherProps }) => (
<View>
<Text>{isLoggedIn ? 'Log In' : 'Log Out'}</Text>
</View>
);
- If you want to pass isLoggedIn as true, you can do so by just writing the prop name:
// recommended
const OtherComponent = () => (
<SomeComponent isLoggedIn />
);
// not recommended
const OtherComponent = () => (
<SomeComponent isLoggedIn={true} />
);
- In some cases, you may want to pass on all of the other props. You can use the spread operator in such a case:
const SomeButton = ({ type , ...other }) => {
const className = type === "blue" ? "BlueButton" : "GrayButton";
return <button className={className} {...other} />;
};
推薦閱讀
- 深入淺出Java虛擬機:JVM原理與實戰
- C語言最佳實踐
- Full-Stack Vue.js 2 and Laravel 5
- 深度強化學習算法與實踐:基于PyTorch的實現
- 網站構建技術
- Elasticsearch Server(Third Edition)
- Learning Unity 2D Game Development by Example
- C#實踐教程(第2版)
- 微信小程序全棧開發技術與實戰(微課版)
- Java EE企業級應用開發教程(Spring+Spring MVC+MyBatis)
- MINECRAFT編程:使用Python語言玩轉我的世界
- R語言:邁向大數據之路(加強版)
- jQuery技術內幕:深入解析jQuery架構設計與實現原理
- 現代CPU性能分析與優化
- Greenplum構建實時數據倉庫實踐