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

时间:2019-04-02 17:33:33

标签: reactjs functional-programming components children

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

当然没问题,如果您没有重新定义shouldComponentUpdate或使用Scaffold( body: Center( child: Container( margin: const EdgeInsets.all(10.0), color: Colors.yellow, height: 100, child: Banner( message: "hello", location: BannerLocation.topEnd, color: Colors.red, child: Center(child: Text("Hello, banner!"),), ), ), ), );

,您只需要知道它会重新渲染子级。
React.memo

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