React Ref
No estes confundido con Reason ref
, la función de idioma que permite la mutación.
El A ReasonReact ref
sera solo otra variable de instancia. Usted escribiría como ReasonReact.reactRef
si se une a un componente personalizado, y Dom.element
si se une a un elemento React DOM.
type state = {
isOpen: bool,
mySectionRef: ref(option(ReasonReact.reactRef))
};
let setSectionRef = (theRef, {ReasonReact.state}) => {
state.mySectionRef := Js.Nullable.toOption(theRef);
/* wondering about Js.Nullable.toOption? See the note below */
};
let component = ReasonReact.reducerComponent("MyPanel");
let make = (~className="", _children) => {
...component,
initialState: () => {
isOpen: false,
mySectionRef: ref(None),
},
reducer: /* ... */,
render: (self) => <Section1 ref={self.handle(setSectionRef)} />
};
Attaching to a React DOM element looks the same: state.mySectionRef = {myDivRef: Js.Nullable.toOption(theRef)}
.
Nota como referencias ReactJS pueden ser nulas. Esa es la razón theRef
y myDivRef
se convierten a partir de una JS nullable en un OCaml opción
(algunos/ningunos). ¡Cuando usted usa la referencia, Usted esta obligado a manejar el caso nulo a través de switch
, que evita sutiles errores!
Usted debe seguir la convención de InstanceVars en le selección anterior para la referencia.
ReasonReact ref only accept callbacks. The string ref
from ReactJS is deprecated.
We also expose an escape hatch ReasonReact.refToJsObj
of type ReasonReact.reactRef => Js.t {..}
, which turns your ref into a JS object you can freely use; this is only used to access ReactJS component class methods.
permita handleClick = (event, self) =>
switch (self.state.mySectionRef^) {
| None => ()
| Some(r) => ReasonReact.refToJsObj(r)##someMethod(1, 2, 3) /* I solemnly swear that I am up to no good */
};