React Native에서 html로 로컬 동적 이미지를 로드하는 방법

먼저 react-native-render-html을 사용해야 합니다.

(저는 WebView를 사용하지 않기 때문에 좋은데 이런 WebView는 별로입니다.)

그러나 문제가 있습니다. 이 라이브러리에는 로컬 이미지를 즉시 로드할 수 있는 방법이 없습니다. 이를 위해** 사용자 정의 이미지 태그를 생성하고 HTML 구성 요소에 추가해야 합니다**

이와 같이:

const htmlContent = ` 
  <h1>This HTML snippet is now rendered with native components !</h1>
  <img source="./src/assets/michael.jpg"/>
  <h2>Enjoy a webview-free and blazing fast application</h2>
  <em>Some random sentence!</em>
`;


        <HTML
          renderers={{
            img: (attribs) => {
              const imagePath = attribs.source;
              console.log(imagePath);
              return (
                <Image
                  key={attribs.source}
                  style={styles.imageContainer}
                  source={require('./src/assets/michael.jpg')}
                />
              );
            },
          }}
          source={{html: htmlContent}}
          contentWidth={contentWidth}
        />


여기에서는 renderers prop 내부에 img라는 사용자 정의 태그를 만들고 내가 선택한 이미지 경로가 있는 구성 요소로 정의합니다.

결과는 다음과 같습니다.



그러나 주요 문제는 해결되지 않았습니다. 우리의 목표는 우리가 만든 사용자 지정 태그를 사용하여 로컬 이미지를 동적으로 렌더링하는 것입니다.

이 후에 아마도 당신은 생각할 것입니다:

-"이미지 경로를 소품으로 <img/> 태그에 전달하면 완성입니다!"

맞습니다. 하지만 사용자 정의 태그를 렌더링할 이미지 경로를 전달하려면 어떻게 해야 합니까?
<img> 태그에 이미지 경로가 있는 소스 소품을 추가했습니다.

<img source="./src/assets/michael.jpg"/>

그리고 **attribs**를 매개변수로 추가하는 img 함수 내에서 가져오고 있습니다.

이제 attribs.source를 사용하여 이미지 경로에 액세스할 수 있습니다.

const htmlContent = ` 
  <h1>This HTML snippet is now rendered with native components !</h1>
  <img source="./src/assets/michael.jpg"/>
  <h2>Enjoy a webview-free and blazing fast application</h2>
  <em>Some random sentence!</em>
`;


        <HTML
          renderers={{
            img: (attribs) => {
              const imagePath = attribs.source;
              console.log(imagePath);
              return (
                <Image
                  key={attribs.source}
                  style={styles.imageContainer}
                  source={require('./src/assets/michael.jpg')}
                />
              );
            },
          }}
          source={{html: htmlContent}}
          contentWidth={contentWidth}
        />


콘솔에 다음과 같이 출력됩니다.

"./src/assets/michael.jpg"

이제 18행을 다음과 같이 변경하려고 하면 다음과 같습니다.

require('./src/assets/michael.jpg);

to

require(imagePath);

다음과 같은 오류가 발생합니다.

[Error: TransformError App.js: App.js:Invalid call at line 31: require(imagePath)]

모든 가져오기는 동적 표현식이 아닌 문자열이어야 하기 때문입니다.

아마도 지금 당신은 생각하고 있습니다:

"-만약 그가 미디엄에 글을 쓴다면, require 안에 동적 가져오기를 가져올 수 있는 방법이 있기 때문이겠죠?"

음 ... 아니…

우리가 할 일을 보여 드리겠습니다.

우리가 확실히 알고 있는 한 가지는 일반적으로 다음과 같이 이미지를 가져올 수 있다는 것입니다.

 const imagesList = {
    dwight: require('./src/assets/dwight.jpg'),
    michael: require('./src/assets/michael.jpg)
  }

const htmlContent = ` 
  <h1>This HTML snippet is now rendered with native components !</h1>
  <img source="./src/assets/michael.jpg"/>
  <h2>Enjoy a webview-free and blazing fast application</h2>
  <em>Some random sentence!</em>
`;


        <HTML
          renderers={{
            img: (attribs) => {
              const imagePath = attribs.source;
              return (
                <Image
                  key={attribs.source}
                  style={styles.imageContainer}
                  source={imagesList[imagePath]}
                />
              );
            },
          }}
          source={{html: htmlContent}}
          contentWidth={contentWidth}
        />


그래서 모든 이미지로 개체를 만들고 있으며 해당 개체의 속성으로 필요합니다.

const imagesList = {
    dwight: require('./src/assets/dwight.jpg'),
    michael: require('./src/assets/michael.jpg)
  }

이제 마침내 사용자 지정 태그의 소스 속성에서 렌더링하려는 이미지를 전달할 수 있습니다.

<img source="michael"/>

또한 이미지 구성 요소를 다음과 같이 수정해야 합니다.

<Image
   key={attribs.source}
   style={styles.imageContainer}
   source={imagesList[imagePath]}
 />

이제 내가 바뀌면

<img source="michael"/>

to

<img source ="dwight"/> 

결과는 다음과 같습니다.



결론



이 솔루션을 구현하는 가장 좋은 방법은 다른 파일에서 imageList 변수를 분리하고 각 이미지와 해당 경로를 수동으로 추가하거나 내가 한 것처럼 모든 어려운 작업을 수행하는 스크립트를 만들 수 있습니다.

자습서에서 이 스크립트를 만드는 방법을 배울 수 있습니다.

프로젝트 소스 코드here를 찾을 수 있습니다.

도움이 되었기를 바랍니다. ;)

좋은 웹페이지 즐겨찾기