1 const RenderAll = (props) => { 2 return( 3 <React.Fragment> 4 {props.children(props)} 5 </React.Fragment> ); 6 }; 7 8 <RenderAll> {() => <h1>hello world</h1>} </RenderAll>
四、提供者模式
1 <Tabs> 2 <TabItem>One</TabItem> 3 <TabItem>Two</TabItem> 4 <TabItem>Three</TabItem> 5 </Tabs>
1 const TabItem = (props) => { 2 const {active, onClick} = props; 3 const tabStyle = { 4 ‘max-width‘: ‘150px’, 5 color: active ? ‘red‘ : ‘green’, 6 border: active ? ‘1px red solid‘ : ‘0px’, 7 }; 8 return ( <h1 style={tabStyle} onClick={onClick}> 9 {props.children} 10 </h1> ); 11 };
1 class Tabs extends React.Component { 2 state = { activeIndex: 0 } 3 render() { 4 const newChildren =React.Children.map(this.props.children, 5 (child, index) => { 6 if (child.type) {
// 拷贝Tabs的子组件并进行篡改(添加新的逻辑),然后将新的子组件返回出去 7 return React.cloneElement(child, { 8 active: this.state.activeIndex === index, 9 onClick: () => this.setState({activeIndex: index}) 10 }); 11 } else { 12 return child; 13 } 14 }); 15 return ( <Fragment> {newChildren} </Fragment> ); } 16 }
原文:https://www.cnblogs.com/dfzc/p/11404480.html