[英]Types of Components in React (in Total)? [closed]
当我学习“React”时,我开始知道 React 中有两种类型的组件:
现在,在进行一些采访时,我遇到了以下问题:
而且...
现在,我更困惑了,因为我只知道只有两种类型的组件。 那么有人可以帮助我 - 这些其他组件是什么,或者如果它们也是 React 的一部分,那么 React in total what are the different types of Components in React
什么?
A class component is a class with a render method that React will call to get jsx to render and a functional component is a function that React will call passing props to it and the function will return jsx for React to render.
A smart component is a component with logic, if it's a class then maybe the component has local state ( this.state
), if it's a smart functional component then the component may have some hooks ( const [state,setState]=useState(initialState)
)。
一个哑组件只根据传入的 props 生成 jsx,没有任何逻辑,所以一个哑 class 组件只有一个渲染方法,一个哑功能组件没有钩子。
纯组件仅在传递给它的道具发生变化时重新渲染,但是当纯组件具有钩子时,即使道具没有更改(例如在组件中使用useSelector
时),它也可以重新渲染,但从技术上讲,该组件具有副作用并且不是不纯。 纯 class 组件扩展了 React.PureComponent 并且不存在纯功能组件,您可以将功能组件传递给 React.memo 但React.memo(FunctionalComponent)
的结果不是 function。 因此,您可以使用备忘录 HOC 从功能组件制作新的纯组件,但纯组件绝不是 function。
不纯组件可以是具有副作用的组件,例如在 onMount 方法中调用 class 组件中的 api 方法或使用 useEffect 在功能组件中产生效果。 具有任何自己的 state(useState 或 this.state)的组件也不是纯的。
高阶组件类似于 React-Redux 连接和反应备忘录。 它是一个 function 接收一个组件并返回一个新组件。
以下是一些示例(无 class 组件):
//fake api that resolves later const api = () => new Promise((resolve) => setTimeout(() => resolve([1, 2, 3]), 2000) ); //HOC using props.loading to display loading const withLoading = (Component) => (props) => props.loading? 'loading': <Component {...props} />; //pure component will only re render when props change // also dumb component as it only returns jsx // and using HOC React.memo to create List const List = React.memo(function List({ data }) { return <pre>{JSON.stringify(data, undefined, 2)}</pre>; }); //this will display loading using the withLoading HOC const LoadingList = withLoading(List); //functional impure component (has side effect fetching data and local state) const App = () => { //smart component as App uses state and does more than only return jsx const [data, setData] = React.useState({ loading: true }); React.useEffect(() => { api().then((data) => setData({ loading: false, data, }) ); }); return <LoadingList {...data} />; }; ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.