我们可以使用 class 个组件作为 React 中功能组件的子组件吗?
Can we use class components as children for functional components in React?
我们可以将有状态组件作为无状态功能组件的子组件吗?
简答:是的。
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>
当然没问题,您只需要注意,如果您没有重新定义 shouldComponentUpdate 或使用 React.memo
,它会重新渲染子项
shouldComponentUpdate(nextProps) {
return (this.props.val !== nextProps.val);
}
进一步阅读:
https://reactjs.org/docs/react-component.html#shouldcomponentupdate
https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate
我们可以将有状态组件作为无状态功能组件的子组件吗?
简答:是的。
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>
当然没问题,您只需要注意,如果您没有重新定义 shouldComponentUpdate 或使用 React.memo
shouldComponentUpdate(nextProps) {
return (this.props.val !== nextProps.val);
}
进一步阅读: https://reactjs.org/docs/react-component.html#shouldcomponentupdate https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate