3

我正在尝试按照该教程视频在 Android 上为 React Native 制作一个本机模块,但它似乎不完整,我找不到完成它的方法。

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

但我无法在 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。我走对了吗?

4

1 回答 1

4

我想我设法让它发挥作用。诀窍是使用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);
    }
}
于 2018-06-12T01:23:58.470 回答