gpt4 book ai didi

javascript - 如何将类组件转换为函数无状态组件?

转载 作者:行者123 更新时间:2023-12-02 22:41:36 26 4
gpt4 key购买 nike

我正在尝试将类组件转换为函数组件。但这对我来说有点困难。你可以帮帮我吗?

我尝试过这样做,但没有成功:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import MovieCardsList from './MovieCardsList';

function (
props.profiles
props.movies
props.users
) {
return (
<div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">ReactND - Coding Practice</h1>
</header>
<h1>How Popular is Your Favorite Movie?</h1>
<MovieCardsList profiles={profiles} movies={movies} users={users} />
</div>
);
}

export default App;

这里是部分代码:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import MovieCardsList from './MovieCardsList';

class App extends Component {
render() {
return (
<div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">ReactND - Coding Practice</h1>
</header>
<h1>How Popular is Your Favorite Movie?</h1>
<MovieCardsList profiles={profiles} movies={movies} users={users} />
</div>
);
}
}

export default App;

我已经接近解决方案了吗?任何帮助,我很感激。提前致谢。

最佳答案

只需进行最小的更改:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import MovieCardsList from './MovieCardsList';

function App(props) {
return (
<div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">ReactND - Coding Practice</h1>
</header>
<h1>How Popular is Your Favorite Movie?</h1>
<MovieCardsList profiles={props.profiles} movies={props.movies} users={props.users} />
</div>
);
}

export default App;

您还可以使用 {...props} 对象展开将它们设置在 MovieCardsList 上,或使用对象解构 ({ profile, movie, users }) 来替换 ( Prop )。我个人会如何做:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import MovieCardsList from './MovieCardsList';

export default ({ profiles, movies, users }) => (
<div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">ReactND - Coding Practice</h1>
</header>
<h1>How Popular is Your Favorite Movie?</h1>
<MovieCardsList profiles={profiles} movies={movies} users={users} />
</div>
);

关于javascript - 如何将类组件转换为函数无状态组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58565819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com