我们可以在React中使用类组件作为子功能组件吗?

问题描述 投票:0回答:2

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

reactjs functional-programming components children
2个回答
1
投票

简短回答:是的。

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>

1
投票

当然没问题,如果你没有重新定义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

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.