Define methods for React components through props.
Sometimes we want to encapsulate some functionality(method) into a component because it is the best place for having related data or other reasons. For example, we want a notification component with method
send, or a form component with method
Since we defined a method for a component, it should be invoked by other components. How? It seems that we can use
ref to reference that component, but ...
ref is bad
There are enough articles to argue about this. For me, one key point is that normal class method cannot be inherited when component is extended with HOC mode.
This package exports two HOCs:
defineMethod(name, definition)is used to define method for a component
definitionis such a function:
(props) => (...args) => any
withMethod(name)is used to 'extract' and invoke a method
import React Component from 'react'import withMethod defineMethod from 'react-method'import compose withHandlers from 'recompose'const LoginForm =onSubmit<form =>...<button>inner submit</button></form>const LoginView =submitForm<div><LoginForm =/><button =>outer submit</button></div>