forked from osdio/react-native-html-render
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
executable file
·95 lines (81 loc) · 1.79 KB
/
index.js
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import React, {
Component,
PropTypes
} from 'react'
import htmlToElement from './htmlToElement'
import {
Linking,
StyleSheet,
View,
} from 'react-native'
const boldStyle = { fontWeight: '500' }
const italicStyle = { fontStyle: 'italic' }
const codeStyle = { fontFamily: 'Menlo' }
const baseStyles = StyleSheet.create({
b: boldStyle,
strong: boldStyle,
i: italicStyle,
em: italicStyle,
pre: codeStyle,
code: codeStyle,
a: {
fontWeight: '500',
color: '#007AFF',
},
})
class HtmlView extends Component {
constructor() {
super()
this.state = {
element: null,
}
}
componentDidMount() {
this.mounted = true
this.startHtmlRender(this.props.value)
}
componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value) {
this.startHtmlRender(nextProps.value)
}
}
componentWillUnmount() {
this.mounted = false
}
startHtmlRender(value) {
if (!value) {
this.setState({ element: null })
}
const opts = {
linkHandler: this.props.onLinkPress,
styles: Object.assign({}, baseStyles, this.props.stylesheet),
customRenderer: this.props.renderNode,
}
htmlToElement(value, opts, (err, element) => {
if (err) {
this.props.onError(err)
}
if (this.mounted) {
this.setState({ element })
}
})
}
render() {
if (this.state.element) {
return <View children={this.state.element} {...this.props} />
}
return <View />
}
}
HtmlView.propTypes = {
value: PropTypes.string,
stylesheet: PropTypes.object,
onLinkPress: PropTypes.func,
onError: PropTypes.func,
renderNode: PropTypes.func,
}
HtmlView.defaultProps = {
onLinkPress: url => Linking.openURL(url),
onError: console.error.bind(console),
}
export default HtmlView