Hướng Dẫn Viết Một ImageGallery Component ReactJS

Bài viết này không hướng dẫn các bạn làm quen với việc viết Component trong ReactJS, mà là sử dụng API của ReactJS để xử lý Component kiểu truyền tham số cần xử lý là children

Yêu cầu của bài như sau, hãy viết một React Component cho đầu ra là một image gallery hình ảnh, có mũi tên next, previous, có nút autoplay, dots navigation:

<ImageGallery autoPlay={true}>
          <img src="https://place-hold.it/350x150?text=1" alt="1" />
          <img src="https://place-hold.it/350x150?text=2" alt="2" />
          <div className="third">
            <img src="https://place-hold.it/350x150?text=3" alt="3" />
            <span>
              <img src="https://place-hold.it/350x150?text=4" alt="3" />
            </span>
          </div>
          <p>1234</p>
        </ImageGallery>

Vấn đề cần xử lý của bài toán này là xử lý lưu tất cả hình ảnh lấy được vào một mảng, là xem như bước kế tiếp là xây dựng một Slider theo ý tưởng của bạn

Ở đây children của Component này là nguyên 1 cụm html:

<img src="https://place-hold.it/350x150?text=1" alt="1" />
          <img src="https://place-hold.it/350x150?text=2" alt="2" />
          <div className="third">
            <img src="https://place-hold.it/350x150?text=3" alt="3" />
            <span>
              <img src="https://place-hold.it/350x150?text=4" alt="3" />
            </span>
          </div>
          <p>1234</p>

ReactJS đã cung cấp cho mình một api để xử lý việc này là  React.Children.forEach cho phép duyệt qua từng con của children và kiểm tra dữ liệu của từng node con. Dựa vào đó mình viết 1 hàm để parser cái chidren ra và kiểm tra lưu hình ảnh vào 1 mảng là bài toán đã được giải quyết. Hàm getImageRecursive ở bên dưới:

getImageRecursive(children, imagesData = []) {
    React.Children.forEach(children, (child, index) => {
      if (child.type === "img") {
        imagesData.push(child.props.src);
      } else {
        if (child.props && typeof child.props["children"] !== "undefined") {
          this.getImageRecursive(child.props.children, imagesData);
        }
      }
    });
  }

Hàm này đầu vào là children của React Component và 1 mảng imagesData để lưu hình ảnh được tìm thấy.

Link codesandbox: https://codesandbox.io/s/pjwy7lw4lq

Rate this post

You May Also Like

About the Author: truongluu

Leave a Reply

Your email address will not be published. Required fields are marked *