-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
57 lines (53 loc) · 1.21 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import * as React from "react";
/**
* 多语言组件
* @author rivertwilight
* 若props包含子节点作为词典Provider,不包含作为Consumer
*/
const { Provider, Consumer } = React.createContext({
dictionary: {},
language: null,
});
interface Pro {
dictionary: dictionary;
language: string;
children: JSX.Element | JSX.Element[] | null;
}
interface Con {
[dicIndex: string]: true;
}
export default function Text({
dictionary,
language,
children,
...props
}: Pro | Con): JSX.Element {
if (children) {
return <Provider value={{ language, dictionary }}>{children}</Provider>;
}
const key = Object.keys(props).filter(
(item) =>
Object.prototype.toString.call(props[item]) ===
"[object Boolean]" ||
Object.prototype.toString.call(props[item]) === "[object Array]"
)[0];
return (
<Consumer>
{(value) => {
if (
Object.prototype.toString.call(props[key]) ===
"[object Array]"
) {
let templeStr = value.dictionary[key][value.language];
let i = 0;
while (templeStr.match(/\%s/)) {
templeStr = templeStr.replace(/\%s/, props[key][i]);
i++;
}
return templeStr;
}
return value.dictionary[key][value.language];
}}
</Consumer>
);
}