How to Measure Custom Native Component in React Native on Android

I want to create my own custom component that displays one line of text. The length of this text is dynamic and the font and size are customizable.

When I put my custom component in standard <View />

, the size constraints in View.onMeasure

(native) are zero for the height, and that's it MeasureSpec.EXACTLY

. Returning any non-zero height in View.onMeasure

does nothing.

class App extends React.Component<{}, undefined> {
  render() {
    return (
      <View style={{
          flex: 1,
        }}>
        <CustomComponent />
      </View>
    )
  }
}

      

How can I let my own custom view measure itself and expose this to React Native during measure and compose?

+3


source to share


1 answer


After much effort and effort, I found the answer.

You need to override ViewManager.getShadowNodeClass

and provide a custom implementation ReactShadowNode

.

Same,



public class CustomShadowNode extends LayoutShadowNode implements YogaMeasureFunction {
    public CustomShadowNode() {
        this.setMeasureFunction(this);
    }

    @Override
    public long measure(
      YogaNode node,
      float width, YogaMeasureMode widthMode,
      float height, YogaMeasureMode heightMode) {
      return YogaMeasureOutput.make(0, 0);
    }
}

      

I used LayoutShadowNode

as it seems to handle standard layouts and stylistic props.

I wrote in more detail about this here .

+3


source







All Articles