我们可以将有状态组件作为无状态功能组件的子代吗?
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(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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.