[英]ReactJS: Stateful children in stateless component
在無狀態組件中包含有狀態的子項是否會使該組件不再無狀態?
不,不是。
與具有狀態的組件關聯的生命周期方法應獨立於其在組件層次結構中的位置而工作,否則,事情將以不可預測的方式中斷。
這證明無狀態組件具有類的支持實例,因此它們可以使用ref
和生命周期方法:
class StatefulComponent extends React.Component { componentDidMount() { this.wrapper.classList.add("highlight"); } render() { return ( <div ref={ref => this.wrapper = ref}> Stateful (red outline due to class being added) {this.props.children} </div> ); } } const StatelessComponent = props => ( <div> Stateless (black outline) {props.children} </div> ); ReactDOM.render( <StatefulComponent> <StatelessComponent> <StatefulComponent /> </StatelessComponent> </StatefulComponent>, document.getElementById("app"));
div { padding: 20px; outline: 1px solid; } .highlight { outline-color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>
國家是由組成部分私人管理的財產,因此, 組成無國籍狀態是由其自己而不是其父母或子女決定的。
無狀態組件中沒有可用的生命周期掛鈎,而它們仍可繼續在其子代中正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.