我尝试过构建原生ui组件,但它经常受到欢迎。该组件似乎没有以react-native的形式呈现。
尽管如此,对于这个问题,我特意尝试在反应原生中呈现Android片段,但没有任何东西出现。示例代码:
public class PreferenceViewManager extends SimpleViewManager<FrameLayout> {
public static final String REACT_CLASS = "RCTPreferenceView";
private WeakReference<Activity> activityWeakReference;
public PreferenceViewManager(WeakReference<Activity> activityWeakReference) {
this.activityWeakReference = activityWeakReference;
}
@Override
public String getName() {
return REACT_CLASS;
}
@Override
public FrameLayout createViewInstance(ThemedReactContext context) {
Log.d(REACT_CLASS, "PreferenceView createViewInstance");
final FrameLayout view = new FrameLayout(context);
view.setId(View.generateViewId());
// Testing if the view does get rendered, it should show white even if fragment is not rendered!
view.setBackgroundColor(Color.WHITE);
// not sure where to call fragment beginTransaction properly, the code below is just for testing
view.postDelayed(new Runnable() {
@Override
public void run() {
onAfterUpdateTransaction(view);
}
}, 2000);
return view;
}
@Override
public void onAfterUpdateTransaction(FrameLayout view) {
super.onAfterUpdateTransaction(view);
activityWeakReference.get().getFragmentManager().beginTransaction().replace(view.getId(), new PreferenceView()).commit();
Log.d(REACT_CLASS, "PreferenceView Commit"); // for debug
}
}
使用上面的视图管理器,视图所在的位置甚至不是白色,表示FrameLayout本身不会被渲染。
我做错了什么?
答案 0 :(得分:1)
实际上,您的方向正确。之所以不渲染FrameLayout是因为您没有在ReactNative中显式添加样式以指定其高度和宽度。但是,即使这样,您的片段也不会被渲染。您可以执行一些更改来呈现片段。
在ViewManager中,执行以下几项更改:
@Override
public FrameLayout createViewInstance(ThemedReactContext context) {
final FrameLayout view = new FrameLayout(context);
MyFragment fragment = MyFragment.newInstance();
// Add the fragment into the FrameLayout
reactContext.getCurrentActivity().getFragmentManager()
.beginTransaction()
.add(fragment, "My_TAG")
.commit();
// Execute the commit immediately or can use commitNow() instead
reactContext.getCurrentActivity().getFragmentManager().executePendingTransactions();
// This step is needed to in order for ReactNative to render your view
addView(fragment.getView(), LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
return view;
}
然后在您的ReactNative组件中
class ExampleComponent extends React.Component {
render() {
return (
<View>
<Text>Hello</Text>
<RCTPreferenceView
{...this.props}
style={{ height: "80%", width: "100%" }}
/>
</View>
);
}
}
希望这可以帮助正在尝试在ReactNative视图内渲染片段的人
答案 1 :(得分:-1)