JSX
類似于 Android 中的 xml,完成布局的同時,包含了邏輯部分。
public render() {
return (
<View>
<FlatList
data={routeMap}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={SeparatorLine}
renderItem={({ item }) => (this.renderItem(item, () => {
// @ts-ignore
this.props.navigation.navigate(item.name);
}))}
/>
</View>
);
}
其實這個本質上是一種語法糖,在編譯期會被轉成 JS Object。例如
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
轉換后:
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
Component
React 中最核心最基礎的概念。可以說,在 React 中,Everything is Component。
export interface ProjectCountProps {
count: number
};
export interface ProjectCountState {
text: string
}
class ProjectCountShow extends React.Component<ProjectCountProps, ProjectCountState> {
constructor(props: ProjectCountProps) {
super(props)
this.state = {text: ''}
}
componentDidMount() {
this.setState({text: "a"});
}
public render () {
return (
<div>
<h1>組件狀態: {this.state.text}</h1>
<h2>統計: {this.props.count}</h2>
</div>
)
}
};
Props & State
Component 涉及到兩個重要概念 Props 和 State
- Props 組件的屬性。它應該是 Component 對外提供,由外部傳入,內部只讀。
- State 組件的狀態。只在內部維護,對外不可見。State 的變化會觸發組件的重新渲染。
函數式組件
復雜的狀態管理,會增加代碼的維護成本,降低可讀性。所以業務開發中盡量實現無狀態組件,也叫函數式組件。
export interface ProjectCountProps {
count: number
};
const PeojectCountF = (props: ProjectCountProps) => {
return (
<div>
<h2>統計: {props.count}</h2>
</div>
)
}
HOC(Higher-Order Component)
高階組件:輸入一個組件,返回一個新組件。
高階組件非常適合 UI 和邏輯解耦的場景。例如實現一個基礎控件組件,但是實際的業務邏輯處理放在高階組件內。
export interface UserComponentProps {
name: string;
}
class UserComponent extends Component<UserComponentProps> {
render() {
return (
<View>
<Text>{this.props.name}</Text>
</View>
);
}
}
export default (userComponent: UserComponent) => {
class UserStoreComponent extends Component<{}, { name: string | null }> {
constructor(props: any) {
super(props);
this.state = { name: null }
}
componentWillMount() {
let name = localStorage.getItem('name');
this.setState({ name });
}
render() {
return <UserComponent name={this.state.name || ''} />
}
}
return UserStoreComponent;
}
組件的生命周期
Component生命周期
生命周期分為兩個階段:
- 掛載階段
- 更新階段
掛載階段
顧名思義,掛載階段即一個新的組件掛到組件樹的過程中,所觸發的生命周期方法。
- componentWillMount: 掛載開始之前調用,也就是 render 方法執行之前調用。可以在這個方法中執行數據準備操作
- componentDidMount: 掛載完成
- componentWillUnmount: 組件從樹中被移除
更新階段
更新階段是組件的變化的過程。當 props 或者 state 發生變化時自動觸發相應方法。
- shouldComponentUpdate(nextProps, nextState): 可以根據情況自行控制是否執行渲染
- componentWillReceiveProps(props): 從父組件收到新的 props 變化之前調用
- componentWillUpdate: 重新渲染之前調用
- componentDidUpdate: 每次重新渲染完成后調用
Smart vs Dumb 組件
掌握以上內容之后,基于 React 的開發基本沒有太大障礙。 還有一些深入的細節例如 ref、context 等不建議直接使用,前端技術棧工具環境特別豐富,各種場景都能找到對應的解決方案。
但是從業務開發的角度看,如果我們的業務場景還不是太復雜,還不太需要引入狀態管理框架來管理數據狀態的時候,我們如何劃分和組織 Component 呢?
從邏輯上我們可以將組件劃分為 Smart 和 Dumb 組件。
- Dumb 組件只根據 props 渲染對應的 UI 元素,不維護內部 state 狀態。等效于函數式組件。 這種組件更易于維護、復用、測試,是穩定性的保障。
- Smart 組件: 僅有 Dumb 組件是不能完成整體業務邏輯的,所以可以在 Smart 組件內完成邏輯部分的操作,然后分發給 Dumb 組件。