React父组件向子组件通信

Posted by 大白菜 2020-09-13T08:58:48.000Z

有两种方法:1.利用回调函数。2.利用自定义事件机制:这种方法更通用,设计组件时考虑加入事件机制往往可以达到简化组件API的目的。

在React中,可以使用任意一种方法,在简单场景下使用自定义事件过于复杂,一般利用回调函数。

class ListItem extends Component {
 static contextTypes = {
   color: PropTypes.string,
 }

 render () {
   return (
     <li style={{ background: this.context.color }}></li>
   )
 }
}