简体   繁体   中英

How to reuse functionality of one component to another component in React

I am looking at patterns about reusing code in react and I came across this approach render props . One thing I don't understand here is how do you actually reuse a function, I understand how the state is being shared but if you want to reuse also some function how do you do that? I am posting some sample code that I got from official site of React and added an extra function.

class Cat extends React.Component {
      render() {
        const mouse = this.props.mouse;
        return (
          <img src="/cat.jpg" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
        );
      }
    }

    class Mouse extends React.Component {
      constructor(props) {
        super(props);
        this.handleMouseMove = this.handleMouseMove.bind(this);
        this.state = { x: 0, y: 0 };
      }

      handleMouseMove(event) {
        this.setState({
          x: event.clientX,
          y: event.clientY
        });
      }

      doSomethingElse(){ 
        return 1;
      }


      render() {
        return (
          <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>

            {/*
              Instead of providing a static representation of what <Mouse> renders,
              use the `render` prop to dynamically determine what to render.
            */}
            {this.props.render(this.state)}
          </div>
        );
      }
    }

    class MouseTracker extends React.Component {
      render() {
        return (
          <div>
            <h1>Move the mouse around!</h1>
            <Mouse render={mouse => (
              <Cat mouse={mouse} />
            )}/>
          </div>
        );
      }
    }

So my question is how do I re-use doSomethingElse() in some other component for ex in this case in Cat component! Also I am having some difficulties breaking down this stm: {this.props.render(this.state)} how is this working?

Best way to implement this would be creating a separate global component which does this functionality.

Suppose in components.js , you have :

export const  doSomethingElse = () => { 
        return 1;
      }

And wherever you want it you can do by ,

In Cat.js :

import {doSomethingElse} from 'component.js';

doSomethingElse();

Even you can make like a view component like :

export const displayTime = (time) => (
<View>
<Text>{time}</Text>
</View>

)

And you can import in Dog.js like :

import {displayTime} from 'component.js';


render(){
return(
<View>
{this.displayTime('12:00PM');}
</View>
)
}

Hope it helps. feel free for doubts

In fact :

  1. any prop is possibly a function render(), it's not only the prop render : https://en.reactjs.org/docs/render-props.html

It's important to remember that just because the pattern is called “render props” you don't have to use a prop named render to use this pattern. In fact, any prop that is a function that a component uses to know what to render is technically a “render prop”.

  1. I explain you how work in the design pattern render prop

{this.props.render(this.state)} // It will execute the function (mouse) => Cat mouse={mouse}/> and will instance the component Cat/> with props which are the states of the component Mouse/>

  1. For example, if you want to pass the function doSomethingElse() to the child component , you could do :

     class Mouse extends React.Component { doSomethingElse(){ return 1; } render() { return ( <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}> {this.props.render(this.state, this.doSomethingElse)} </div> ); } } class MouseTracker extends React.Component { render() { return ( <div> <h1>Move the mouse around!</h1> <Mouse render={(mouse, doSomethingElse, ...props) => ( <Cat mouse={mouse} doSomethingElse={doSomethingElse} {...props} /> // Possibly others props if you want )}/> </div> );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM