将React功能组件转换为React类组件

发布于 2025-02-08 11:55:47 字数 2352 浏览 3 评论 0原文

我正在学习反应,需要你们的帮助。 我想将我的React Hook函数转换为React类组件。

反应钩;

const Card = () => {
const [model, setModel] = useState(false);
const [tempData, setTempdata] = useState([]);
const getData = (img, title, desc, votes, comments, views) => {
    let tempData = [img, title, desc, votes, comments, views];
    setTempdata(item => [1, ...tempData]);
    return setModel(true);
}
return(
    <>
        <section className='py-4 py-lg-5 container'>
            <div className='row justify-content-center align-item-center'>
                {data.cardData.map((item, index) => {
                    return(
                        <div className='col-11 col-md-6 col-lg-3 mx-0 mb-4' key={index} onClick={() => getData(item.imgSrc, item.title, item.desc, item.votes, item.comments, item.views)}>
                            <div className="card p-0 over-flow-hidden h-100 shadow bg-transparent">
                                <img className="card-img-top" src={item.imgSrc} alt=""></img>
                                <div className="card-body bg-dark">
                                    <small className="text-white">{item.title}</small>
                                    <small className="text-muted card-detail">
                                        <small className='text-muted'><FaArrowUp className='card_icons'/>{item.votes}</small>
                                        <small className='text-muted'><FaRegCommentAlt className='card_icons card_icon2' />{item.comments}</small>
                                        <small className='text-muted'><FaRegEye className='card_icons card_icon3' />{item.views}</small>
                                    </small>
                                </div>          
                            </div>
                        </div>
                    )
                })}
                
            </div>
        </section>
        {
            model === true ? <Model img={tempData[1]} title={tempData[2]} desc={tempData[3]} votes={tempData[4]} comments={tempData[5]} views={tempData[5]} hide={() => setModel(false)} />: ''
        }
    </>
)

}

我尝试过,但它没有用。请帮助我这样做。

I am learning react and need some help from you guys.
I wants need to convert my react hook function to react class component.

React Hook ;

const Card = () => {
const [model, setModel] = useState(false);
const [tempData, setTempdata] = useState([]);
const getData = (img, title, desc, votes, comments, views) => {
    let tempData = [img, title, desc, votes, comments, views];
    setTempdata(item => [1, ...tempData]);
    return setModel(true);
}
return(
    <>
        <section className='py-4 py-lg-5 container'>
            <div className='row justify-content-center align-item-center'>
                {data.cardData.map((item, index) => {
                    return(
                        <div className='col-11 col-md-6 col-lg-3 mx-0 mb-4' key={index} onClick={() => getData(item.imgSrc, item.title, item.desc, item.votes, item.comments, item.views)}>
                            <div className="card p-0 over-flow-hidden h-100 shadow bg-transparent">
                                <img className="card-img-top" src={item.imgSrc} alt=""></img>
                                <div className="card-body bg-dark">
                                    <small className="text-white">{item.title}</small>
                                    <small className="text-muted card-detail">
                                        <small className='text-muted'><FaArrowUp className='card_icons'/>{item.votes}</small>
                                        <small className='text-muted'><FaRegCommentAlt className='card_icons card_icon2' />{item.comments}</small>
                                        <small className='text-muted'><FaRegEye className='card_icons card_icon3' />{item.views}</small>
                                    </small>
                                </div>          
                            </div>
                        </div>
                    )
                })}
                
            </div>
        </section>
        {
            model === true ? <Model img={tempData[1]} title={tempData[2]} desc={tempData[3]} votes={tempData[4]} comments={tempData[5]} views={tempData[5]} hide={() => setModel(false)} />: ''
        }
    </>
)

}

I have tried but it didn't work. Please help me to do this.

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

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

发布评论

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

评论(1

孤芳又自赏 2025-02-15 11:55:47

对于这样的简单组件,您只需要维护状态并在某些数据上映射确实很容易。

基本上,而不是使用单独的usestate定义每个状态变量,而是在此内定义所有。这可以在班级的构造函数内部,也可以作为成员

定义构造函数内部的状态

class Card extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      /* define your state inside this*/
      model: props.model,
    };
  }
}

将状态定义为班级的成员

class Card extends React.PureComponent {
  state = {
    model: false,
  }
}

如果状态内部状态的初始值取决于您的初始值道具,使用构造方法。
如果状态内部的初始值总是相同的,请使用任何一种方法。

要更新状态,您需要使用this.setstate方法
JSX的其余部分几乎相同。

这是您的组件最终看起来像

import React from 'react';

class Card extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      model: false,
      tempData: [],
    };
  }

  getData = (/* your method parameters here */) => {
    const tempData = [/* define the tempData here */];
    this.setState({
      ...this.state,
      tempData: [1, ...tempData], // dont understand what 1 does here
      model: true,
    });
  }

  render() {
    return (
      <React.Fragment>
        ...your jsx here
      </React.Fragment>
    );
  }
}

export default Card;

For simple components like this, where you just need to maintain state and map over some data is really easy.

Basically, instead of defining each state variable using a seperate useState, define all of then inside this.state. This can be inside the constructor of the class or as a member

Defining state inside the constructor

class Card extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      /* define your state inside this*/
      model: props.model,
    };
  }
}

Defining state as a member of class

class Card extends React.PureComponent {
  state = {
    model: false,
  }
}

If the initial value inside state depends on the your initial props, use the constructor method.
If the initial value inside state is always going to be the same, use either approach.

To update the state, you need to use the this.setState method
And the rest of jsx is pretty much the same.

Here is what your component would finally look like

import React from 'react';

class Card extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      model: false,
      tempData: [],
    };
  }

  getData = (/* your method parameters here */) => {
    const tempData = [/* define the tempData here */];
    this.setState({
      ...this.state,
      tempData: [1, ...tempData], // dont understand what 1 does here
      model: true,
    });
  }

  render() {
    return (
      <React.Fragment>
        ...your jsx here
      </React.Fragment>
    );
  }
}

export default Card;

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