简体   繁体   English

我们可以在React中将类组件用作功能组件的子代吗?

[英]Can we use class components as children for functional components in React?

我们可以将有状态组件作为无状态功能组件的子代吗?

Short answer: yes. 简短的回答:是的。

 class B extends React.Component { render() { return <div>Class Component</div> } } const A = () => <div className="a">Stateless Functional Component <B /></div> ReactDOM.render(<A />, document.getElementById('app')); 
 .a {background: red; padding: 5px;} .a div {background: green;} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div> 

Sure no problem, you just need to be aware that it re-renders the children if you didn't redefined shouldComponentUpdate or to use React.memo 没问题,如果您没有重新定义shouldComponentUpdate或使用React.memo ,您只需要知道它会重新渲染子React.memo

shouldComponentUpdate(nextProps) {
    return (this.props.val !== nextProps.val);
}

For further reading: https://reactjs.org/docs/react-component.html#shouldcomponentupdate https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate 进一步阅读: https : //reactjs.org/docs/react-component.html#shouldcomponentupdate https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我们可以使用 HOC 在 React 中包装功能组件吗 - Can we use HOC to wrap functional components in React 在 React 的基于类的组件中使用带有钩子的功能组件是否安全? - Is that safe to use functional components with hooks inside class based components in React? React class 组件和功能组件可以访问相同的上下文吗? - Can React class components and functional components access the same context? 如何将渲染道具传递给 React 功能组件中的子级? - How can i pass render props to children in React functional components? React 功能组件与 class 组件 - React functional components vs class components 如何将 React 函数式组件转换为类组件 - How to Convert React Functional Components into Class Components 如何将 Class 组件转换为 React 中的功能组件? - How to Convert Class components to functional components in React? Should we use useCallback in every function handler in React Functional Components - Should we use useCallback in every function handler in React Functional Components 在React中导出功能和类组件 - Exporting functional and class components in React 我应该在 React 中使用什么类型的组件:函数式组件还是类基组件? - What type of components should I use in React: functional components or class base components?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM