Page 1 of 1

ray 中 Rjs 间 eventChannel 传递数据示例

Posted: 2025年 Apr 8日 11:30
by crisiron

1、引入带rjs 的组件

Code: Select all

import React, { useState, useEffect } from 'react';
import { View, Text } from '@ray-js/ray';

import { LampCirclePickerColor } from '@ray-js/components-ty-lamp';

import DemoRjs from '../Component/demoRjs';

import styles from './index.module.less';

const DemoBlock = ({ title, children }) => (
  <View className={styles.demoBlock}>
    <View className={styles.demoBlockTitle}>
      <Text className={styles.demoBlockTitleText}>{title}</Text>
    </View>
    {children}
  </View>
);

export default function Home() {
  const [hs, setHS] = useState({ h: 0, s: 1000 });

  useEffect(() => {
    // 模拟 dp 上报
    setTimeout(() => {
      setHS({
        h: 100,
        s: 1000,
      });
    }, 1000);
  }, []);

  const handleTouchStart = (hsRes: HS) => {
    console.log(hsRes, 'handleTouchStart');
    setHS(hsRes);
  };
  const handleTouchEnd = (hsRes: HS) => {
    console.log(hsRes, 'handleTouchEnd');
    setHS(hsRes);
  };

  return (
    <View className={styles.view}>
      <DemoBlock title="带 eventChannel 用法">
        <LampCirclePickerColor
          hs={hs}
          thumbRadius={15}
          radius={100}
          whiteRange={0.15}
          useEventChannel // eventChannel 一般情况用不到,只有当多个Rjs需要通信时才会用到
          onTouchStart={handleTouchStart}
          onTouchEnd={handleTouchEnd}
        />
      </DemoBlock>
      {/* eventChannel 能力示例,DemoRjs 可用在其他地方,但是需要同时存在,一般情况用不到,只有当多个Rjs需要通信时才会用到 */}
      <DemoRjs />
    </View>
  );
}

2、 DemoRjs 组件具体写法

Code: Select all

// DemoRjs/index.js
/* eslint-disable no-undef */
import Render from './index.rjs';

Component({
  lifetimes: {
    created() {
      this.render = new Render(this);
    },
    ready() {
      this.render.renderChannel();
    },
  },
});

Code: Select all

// DemoRjs/index.json
{
  "component": true
}

Code: Select all

// DemoRjs/index.rjs
export default Render({
 // 这里用来监听 'LampCirclePickerColor 的事件
  renderChannel() {
    const eventChannelName = 'lampCirclePickerColorEventChannel';
    this.instance.eventChannel.on(eventChannelName, (e) => {
    	// 自己处理业务逻辑
      console.log('eventChannel get', e);
    });
  },
});

Code: Select all

// DemoRjs/index.tyml
<view 
    class="container"

</view>

Code: Select all

// DemoRjs/index.tyss
.container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}