改编“ myref”从类组件到功能组件 - react

发布于 2025-02-08 12:14:25 字数 2609 浏览 2 评论 0原文

我正在使用单个产品页面上的工作,可以在其中显示我想要的东西,但使用类组件。为了适应它,我遇到了太多问题,尤其是对于MyRef。 我在适应MyRef的情况下遇到了问题。有人可以帮助我知道如何使其适应功能组件吗?

这是我正在使用的代码。

class SingleProduct extends React.Component{
  
state = { 
    products: [
      {
        "_id": "1",
        "title": "Se perdio Roco",
        "src": [
          "http://flogfotos.miarroba.st/5/0/6/5779506/822.jpg",
          "https://upload.wikimedia.org/wikipedia/commons/d/d5/Bianca_8_Meses.jpg",
          "https://sumedico.blob.core.windows.net/images/2020/08/19/perrosboxerblanco.jpg",
          "http://perros.mascotahogar.com/Imagenes/boxer-blanco.jpg"
        ],
        "zone": "Yerba Buena, Tucumán",
        "description": "Perdido desde dia sabado 17 de Junio cerca del Solar del Cerro. Lleva puesto su cadena como se ve en las fotos. Reacciona al llamado de Roco. Es muy cariñoso",
        "condition": "No Encontrado",
        "count": 1
      }
    ],
    index: 0
  };

  myRef = React.createRef();

  handleTab = index =>{
    this.setState({index: index})
    const images = this.myRef.current.children;
    console.log(this.myRef.current.children)
    for(let i=0; i<images.length; i++){
      images[i].className = images[i].className.replace("active", "");
    }
    images[index].className= "active"
  };

  componentDidMount(){
    const {index} = this.state;
    this.myRef.current.children[index].className = "active";
  }

  render () {
    const {products, index} = this.state;
    return(
      <div className='app'>
        {
          products.map(item =>(
            <div className='details' key={item._id}>
              <div className='big-img'>
                <img src={item.src[index]} alt=""/>
              </div>

            <div className='box'>
              <div className='row'>
                <h2>{item.title}</h2>
                <p>{item.zone}</p>
                <span>{item.condition}</span>
              </div>

              <p>{item.description}</p>

              <div className="thumb" ref={this.myRef}>
                {
                  item.src.map((img, index) =>(
                    <img src={img} alt="" key={index}
                    onClick={() => this.handleTab(index)}
                    />
                  ))
                }
              </div>
              <button className='cart '>Ponte en contacto con el dueño</button>

            </div>
            </div>
          ))
        }
      </div>
    )
  }

}

I'm working on a single product page where I could manage to show what I want but using class components. To adapt it, I'm having too many problems, especially with myRef.
I am having problems adapting myRef. Could someone help me to know how to adapt it to work with functional components?

this is the code I am working with.

class SingleProduct extends React.Component{
  
state = { 
    products: [
      {
        "_id": "1",
        "title": "Se perdio Roco",
        "src": [
          "http://flogfotos.miarroba.st/5/0/6/5779506/822.jpg",
          "https://upload.wikimedia.org/wikipedia/commons/d/d5/Bianca_8_Meses.jpg",
          "https://sumedico.blob.core.windows.net/images/2020/08/19/perrosboxerblanco.jpg",
          "http://perros.mascotahogar.com/Imagenes/boxer-blanco.jpg"
        ],
        "zone": "Yerba Buena, Tucumán",
        "description": "Perdido desde dia sabado 17 de Junio cerca del Solar del Cerro. Lleva puesto su cadena como se ve en las fotos. Reacciona al llamado de Roco. Es muy cariñoso",
        "condition": "No Encontrado",
        "count": 1
      }
    ],
    index: 0
  };

  myRef = React.createRef();

  handleTab = index =>{
    this.setState({index: index})
    const images = this.myRef.current.children;
    console.log(this.myRef.current.children)
    for(let i=0; i<images.length; i++){
      images[i].className = images[i].className.replace("active", "");
    }
    images[index].className= "active"
  };

  componentDidMount(){
    const {index} = this.state;
    this.myRef.current.children[index].className = "active";
  }

  render () {
    const {products, index} = this.state;
    return(
      <div className='app'>
        {
          products.map(item =>(
            <div className='details' key={item._id}>
              <div className='big-img'>
                <img src={item.src[index]} alt=""/>
              </div>

            <div className='box'>
              <div className='row'>
                <h2>{item.title}</h2>
                <p>{item.zone}</p>
                <span>{item.condition}</span>
              </div>

              <p>{item.description}</p>

              <div className="thumb" ref={this.myRef}>
                {
                  item.src.map((img, index) =>(
                    <img src={img} alt="" key={index}
                    onClick={() => this.handleTab(index)}
                    />
                  ))
                }
              </div>
              <button className='cart '>Ponte en contacto con el dueño</button>

            </div>
            </div>
          ))
        }
      </div>
    )
  }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三月梨花 2025-02-15 12:14:25

首先,您有两个状态变量。
将其转换为功能组件语法。

首先,您需要

import { useState, useRef, useEffect } from 'react';

const [products, setProducts] = useState([
  {
    "_id": "1",
    "title": "Se perdio Roco",
    "src": [
      "http://flogfotos.miarroba.st/5/0/6/5779506/822.jpg",
      "https://upload.wikimedia.org/wikipedia/commons/d/d5/Bianca_8_Meses.jpg",
      "https://sumedico.blob.core.windows.net/images/2020/08/19/perrosboxerblanco.jpg",
      "http://perros.mascotahogar.com/Imagenes/boxer-blanco.jpg"
    ],
    "zone": "Yerba Buena, Tucumán",
    "description": "Perdido desde dia sabado 17 de Junio cerca del Solar del Cerro. Lleva puesto su cadena como se ve en las fotos. Reacciona al llamado de Roco. Es muy cariñoso",
    "condition": "No Encontrado",
    "count": 1
  }
])
const [index, setIndex] = useState(0)

使用“ USEREF”钩中的功能语法中的React模板参考导入所有挂钩。

const myRef = useRef()

功能组件语法中的“ componentDidmount”等于“ useffect” useffect” hook witt

useEffect(() => {
      myRef.current.children[index].className = "active";
}, [])

functional component语法中的空数组依赖项您不需要渲染方法来返回JSX代码,您只需返回所需的JSX时,当您从方法中返回任何值时,

这是使用功能组件语法的组件的一个工作示例

import { useState, useRef, useEffect } from "react";

export default function SingleProduct() {
const [products, setProducts] = useState([
    {
        _id: "1",
        title: "Se perdio Roco",
        src: [
            "http://flogfotos.miarroba.st/5/0/6/5779506/822.jpg",
            

"https://upload.wikimedia.org/wikipedia/commons/d/d5/Bianca_8_Meses.jpg",
            "https://sumedico.blob.core.windows.net/images/2020/08/19/perrosboxerblanco.jpg",
            "http://perros.mascotahogar.com/Imagenes/boxer-blanco.jpg",
        ],
        zone: "Yerba Buena, Tucumán",
        description:
            "Perdido desde dia sabado 17 de Junio cerca del Solar del Cerro. Lleva puesto su cadena como se ve en las fotos. Reacciona al llamado de Roco. Es muy cariñoso",
        condition: "No Encontrado",
        count: 1,
    },
]);

const [index, setIndex] = useState(0);

const myRef = useRef();

useEffect(() => {
    myRef.current.children[index].className = "active";
}, []);

const handleTab = (index) => {
    setIndex(index);
    const images = myRef.current.children;
    console.log(myRef.current.children);
    for (let i = 0; i < images.length; i++) {
        images[i].className = images[i].className.replace("active", "");
    }
    images[index].className = "active";
};

return (
    <div className="app">
        {products.map((item) => (
            <div className="details" key={item._id}>
                <div className="big-img">
                    <img src={item.src[index]} alt="" />
                </div>

                <div className="box">
                    <div className="row">
                        <h2>{item.title}</h2>
                        <p>{item.zone}</p>
                        <span>{item.condition}</span>
                    </div>

                    <p>{item.description}</p>

                    <div className="thumb" ref={myRef}>
                        {item.src.map((img, index) => (
                            <img
                                src={img}
                                alt=""
                                key={index}
                                onClick={() => handleTab(index)}
                            />
                        ))}
                    </div>
                    <button className="cart ">
                        Ponte en contacto con el dueño
                    </button>
                </div>
            </div>
        ))}
    </div>
);

}

First, you have two stateful variables.
To turn it to functional component syntax.

First you need to import all hooks we need from react

import { useState, useRef, useEffect } from 'react';

const [products, setProducts] = useState([
  {
    "_id": "1",
    "title": "Se perdio Roco",
    "src": [
      "http://flogfotos.miarroba.st/5/0/6/5779506/822.jpg",
      "https://upload.wikimedia.org/wikipedia/commons/d/d5/Bianca_8_Meses.jpg",
      "https://sumedico.blob.core.windows.net/images/2020/08/19/perrosboxerblanco.jpg",
      "http://perros.mascotahogar.com/Imagenes/boxer-blanco.jpg"
    ],
    "zone": "Yerba Buena, Tucumán",
    "description": "Perdido desde dia sabado 17 de Junio cerca del Solar del Cerro. Lleva puesto su cadena como se ve en las fotos. Reacciona al llamado de Roco. Es muy cariñoso",
    "condition": "No Encontrado",
    "count": 1
  }
])
const [index, setIndex] = useState(0)

Template reference in functional syntax with "useRef" hook.

const myRef = useRef()

"componentDidMount" in the functional component syntax equals "useEffect" hook with empty array dependencies

useEffect(() => {
      myRef.current.children[index].className = "active";
}, [])

In functional component syntax you don't need the render method to return the JSX code, you just return the JSX you want as you return any value from a method

This is a working example of your component with functional component syntax

import { useState, useRef, useEffect } from "react";

export default function SingleProduct() {
const [products, setProducts] = useState([
    {
        _id: "1",
        title: "Se perdio Roco",
        src: [
            "http://flogfotos.miarroba.st/5/0/6/5779506/822.jpg",
            

"https://upload.wikimedia.org/wikipedia/commons/d/d5/Bianca_8_Meses.jpg",
            "https://sumedico.blob.core.windows.net/images/2020/08/19/perrosboxerblanco.jpg",
            "http://perros.mascotahogar.com/Imagenes/boxer-blanco.jpg",
        ],
        zone: "Yerba Buena, Tucumán",
        description:
            "Perdido desde dia sabado 17 de Junio cerca del Solar del Cerro. Lleva puesto su cadena como se ve en las fotos. Reacciona al llamado de Roco. Es muy cariñoso",
        condition: "No Encontrado",
        count: 1,
    },
]);

const [index, setIndex] = useState(0);

const myRef = useRef();

useEffect(() => {
    myRef.current.children[index].className = "active";
}, []);

const handleTab = (index) => {
    setIndex(index);
    const images = myRef.current.children;
    console.log(myRef.current.children);
    for (let i = 0; i < images.length; i++) {
        images[i].className = images[i].className.replace("active", "");
    }
    images[index].className = "active";
};

return (
    <div className="app">
        {products.map((item) => (
            <div className="details" key={item._id}>
                <div className="big-img">
                    <img src={item.src[index]} alt="" />
                </div>

                <div className="box">
                    <div className="row">
                        <h2>{item.title}</h2>
                        <p>{item.zone}</p>
                        <span>{item.condition}</span>
                    </div>

                    <p>{item.description}</p>

                    <div className="thumb" ref={myRef}>
                        {item.src.map((img, index) => (
                            <img
                                src={img}
                                alt=""
                                key={index}
                                onClick={() => handleTab(index)}
                            />
                        ))}
                    </div>
                    <button className="cart ">
                        Ponte en contacto con el dueño
                    </button>
                </div>
            </div>
        ))}
    </div>
);

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文