を使用createjs
してキャンバスを作成していますが、このキャンバスにダブルクリックイベントがあります。イベントがトリガーされたときにReactコンポーネントに通知し、カスタム関数で定義された変数に状態を設定します。たとえば、カスタム関数にある「pose.position」に値を設定したいと思います。
私の反応コンポーネント:
const [value, setValue] = useState(null);
const handleEvent = event => {
console.log(value);
};
useEffect(() => {
const ros = new ROSLIB.Ros({
url
});
const viewer = new ROS2D.Viewer({
divID,
width,
height
});
const nav = NAV2D.OccupancyGridClientNav({
ros,
rootObject: viewer.scene,
viewer,
serverName,
continuous
});
setValue(nav.position);
const canvas = divEl.current.children[0];
canvas.addEventListener("dblclick", handleEvent, false);
return () => {
canvas.removeEventListener("dblclick", handleEvnet);
};
}, []);
return <div id={divID} ref={divEl} />;
およびカスタム関数:
this.rootObject.addEventListener("dblclick", function(event) {
// convert to ROS coordinates
const coords = stage.globalToRos(event.stageX, event.stageY);
const pose = new ROSLIB.Pose({
position: new ROSLIB.Vector3(coords)
});
// send the goal
sendGoal(pose);
that.position = pose.position;
// that.mouseClick = true;
console.log("clicked");
});
//I do not know how my React component can get this value, so I just return
return this.position;
問題は、コンポーネントの値が1回だけ設定され、handleEventのlog関数がnullを出力し、値が更新されないことです。値が変更されたことをReactに通知するにはどうすればよいですか?別のものを作成する必要がありますuseEffect(()=>{}, [value])
か?
または
this.rootObject.addEventListener
一部のコンポーネントを再レンダリングするようにreactに通知できるように、でアクションをディスパッチできますか?非反応機能でreduxを使用できますか?
私が見たところ、これを機能させるには2つのオプションがあります
。1)計算position
する部分をReactコンポーネントに配置します。
const [value, setValue] = useState(null);
const handleEvent = event => {
// convert to ROS coordinates
const coords = stage.globalToRos(event.stageX, event.stageY);
const pose = new ROSLIB.Pose({
position: new ROSLIB.Vector3(coords)
});
setValue(pose.position);
};
2)追加のイベントを導入し、コンポーネントでそれをリッスンします。カスタム関数が次のようになるようにします。
this.rootObject.addEventListener("dblclick", function(event) {
// convert to ROS coordinates
const coords = stage.globalToRos(event.stageX, event.stageY);
const pose = new ROSLIB.Pose({
position: new ROSLIB.Vector3(coords)
});
// send the goal
sendGoal(pose);
this.dispatchEvent(new CustomEvent('newposition', { detail: pose.position }));
}
次に、Reactコンポーネントに行を追加します。
canvas.addEventListener("newposition", (e) => setValue(e.detail), false);
どちらの場合も、再レンダリングを防ぐためにvalue
2番目の引数として追加する必要がありますuseEffect
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加