Adding CSS styling to React Native WebView

前端 未结 2 1906
小蘑菇
小蘑菇 2021-02-20 11:31

So I am a bit stumped on this ... I\'m using a WebView in a portion of our app, the reason for the WebView is because we are pulling from an API endpoint that returns to us an H

相关标签:
2条回答
  • 2021-02-20 11:59

    I used this link. The reason I choose this solution over the accepted answer is because I can style html tags using react native styles instead of injecting style declaration string before the actual content.

    const htmlStyles = { p: {fontFamily: 'Lato'} }
    const htmlContent = <H1>My Html</H1>;
    
    <HTML containerStyle={ {margin: 16} }
                    html={ htmlContent } 
                    tagsStyles={ htmlStyles } />
    
    0 讨论(0)
  • 2021-02-20 12:20

    I recently experienced the same issue. It was only occurring for me on iOS, not Android.

    The weirdest part is the inconsistency in replication. I couldn't find any pattern to when the WebView content would be sized differently. Identical HTML would result in font size that was sometimes normal, but other times very tiny.

    My solution came from a (RN 0.47) WebView prop:

    scalesPageToFit?: bool

    Boolean that controls whether the web content is scaled to fit the view and enables the user to change the scale. The default value is true.

    I tried setting scalesPageToFit to false, and voilà, the page stopped scaling down:

    <WebView
      source={{ html: myHtml }}
      scalesPageToFit={false}
    />
    

    The only problem is that this caused my content to be scaled larger than the WebView's container on Android. To fix this, I simply set the scalesPageToFit prop conditionally, based on platform:

    <WebView
      source={{ html: myHtml }}
      scalesPageToFit={(Platform.OS === 'ios') ? false : true}
    />
    

    Worked like a charm for me!

    0 讨论(0)
提交回复
热议问题