ReactJS:无状态组件中的有状态子组件

ReactJS: Stateful children in stateless component

无状态组件中有有状态子组件是否会使组件不再无状态?

简答

不,不是。


与具有状态的组件关联的生命周期方法应该独立于它们在组件层次结构中的位置工作,否则事情会以不可预知的方式中断。

这里证明无状态组件有一个 class 的后备实例,因此它们可以使用 refs 和生命周期方法:

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>

状态是由组件私有管理的属性,因此无状态组件由其自身决定,而不是由其父或子决定。

无状态组件中没有可用的生命周期挂钩,但它们在其子组件中继续按需要工作。