自定义组件和模块
自定义组件
写个 React 组件,在需要渲染的地方通过 nativeName 指定到终端组件名称即可,以终端范例中的 MyView 为例:
1. import React from "react";
2. import { UIManagerModule } from "@hippy/react"
3. 4. export class MyView extends React.Component {
5. constructor(props) {
6. super(props);
7. this.state = {};
8. this.changeColor = this.changeColor.bind(this);
9. }
10. 11. changeColor(color) {
12. // callUIFunction 只能接收一个实际渲染的终端节点
13. UIManagerModule.callUIFunction(this.instance, "changeColor", [color]);
14. }
15. 16. render() {
17. return (
18. <div
19. ref={ref => this.instance = ref} // 设置 ref 方便 changeColor 获取
20. nativeName="MyView" // 必须:将前端组件与终端组件进行绑定
21. {...this.props}
22. >
23. )
24. }
25. }
自定义模块
该范例仅可以在 Android 下运行。 前端扩展模块分为三步: 1. 第一步导入 callNative 或者 callNativeWithPromise 接口 2. 封装调用接口 3. 导出模块
1. // TestModule.js
2. import { callNative, callNativeWithPromise } from "@hippy/react"
3. 4. /*
5. 自定义module
6. */
7. const TestModule = {
8. log(msg) {
9. callNative("TestModule", "log", msg)
10. },
11. helloNative(msg) {
12. callNative("TestModule", "helloNative", msg)
13. },
14. //这个是需要终端回调的
15. helloNativeWithPromise(msg) {
16. return callNativeWithPromise("TestModule", "helloNativeWithPromise", msg);
17. }
18. }
19. 20. export { TestModule }
使用
1. import React from "react";
2. import { Text } from "@hippy/react"
3. import { TestModule } from "./TestModule"
4. 5. //展示自定义Module的使用
6. export default class TestModuleDemo extends React.Component {
7. static defaultProps = {};
8. 9. constructor(props) {
10. super(props);
11. this.state = { hello: "TestModule log" }
12. //调用
13. TestModule.log("hello I am from js");
14. TestModule.helloNative({ hello: "I am from js" })
15. TestModule.helloNativeWithPromise({ hello: "I am from js" })
16. .then(rsp => this.setState({ hello: JSON.stringify(rsp) }));
17. }
18. 19. render() {
20. const { hello } = this.state;
21. return (
22. <Text style={{ color: "red" }}>
23. {hello}
24. </Text>
25. )
26. }
27. }
