render props的简单实用

1.实用目的:

在组件中,如果一个组件的某一个功能需要重复实用,那么就可以使用 render props方法。

2.步骤:

1) 创建某个组件,在组件中提供复用的状态(1.状态 2.修改状态的方法)

     
1.状态  
this.state = { x:0, y:0 }

  

2. 修改方式
mouseXY=e=>{ this.setState({ x:e.clientX, y:e.clientY }) } componentDidMount(){ window.addEventListener('mousemove',this.mouseXY) }

  2)将要复用的状态作为props.render(state)的方法,暴露到组件外部

  

render(){
    return  this.props.render(this.state)
  }

  3)使用返回值 渲染内容

     <Mouse render={mouse =>{
        return <p>{mouse.x} , {mouse.y}  </p>   //mouse指的是从子元素传递过来的this.state数据
      }}></Mouse>

  

猜你喜欢

转载自www.cnblogs.com/ruoxiangli/p/12578617.html
今日推荐