我试图在tutorial video之后为Android上的React Native创建一个Native模块,但它似乎不完整,我找不到解决方法。

我试图显示一个正方形,并在该正方形内显示作为道具传递的文本。

但是我无法在Android的视图内添加TextView。

这是我的SquarePackage.java

public class SquarePackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.<ViewManager>singletonList(new SquareManager());
    }
}


这是我的SquareManager.java

public class SquareManager extends SimpleViewManager<View> {
    public static final String REACT_CLASS = "Square";

    private View view;
    private TextView textView;

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    protected View createViewInstance(ThemedReactContext reactContext) {
        view = new View(reactContext);
        view.setBackgroundColor(Color.BLUE);
        textView = new TextView(reactContext);
        // view.addView(textView); // <-- This does not work, addView not being a method of View
        return view;
    }

    @ReactProp(name = "text")
    public void setTextProp(View view, String prop) {
        // view.setText(prop); // <-- this does not work as I cannot setText on a View
    }
}


到目前为止,我只有一个蓝色的Square。我走对了吗?

最佳答案

我设法使它起作用。诀窍是使用LinearLayout,但我不知道这是否是正确的方法...

public class SquareManager extends SimpleViewManager<LinearLayout> {
    public static final String REACT_CLASS = "Square";

    private LinearLayout linearLayout;
    private TextView textView;

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    protected LinearLayout createViewInstance(ThemedReactContext reactContext) {
      linearLayout = new LinearLayout(reactContext);
      linearLayout.setBackgroundColor(Color.BLUE);
      textView = new TextView(reactContext);
      textView.setTextColor(Color.WHITE);
      linearLayout.addView(textView);
      return linearLayout;
}

    @ReactProp(name = "text")
    public void setTextProp(View view, String prop) {
         textView.setText(prop);
    }
}

08-18 01:25