我们可以将有状态组件作为无状态功能组件的子组件吗?
简短回答:是的。
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