首页 > 解决方案 > 通过 props 禁用效果 react-three-fiber

问题描述

我使用npm 包创建了具有react-three-fiber效果的场景。EffectsComposerGlitchreact-postprocessing

我想使用 html 输入复选框来切换效果的active状态,但是,切换道具的状态不会禁用效果。禁用复选框输入效果的正确方法是什么?Glitchactive

我在这里设置了一个有问题的沙箱 https://codesandbox.io/s/tender-star-lw07h?file=/src/App.tsx:0-1488

这是代码。

import React, {
  Suspense,
  useRef,
  useEffect,
  useState,
  createRef,
  Fragment
} from "react";
import Outline from "./components/Outline";
import { EffectComposer, Glitch, Noise } from "react-postprocessing";
import { Canvas } from "react-three-fiber";
import { OrbitControls } from "drei";
import { Mesh } from "three";
import { GlitchMode } from "postprocessing";

const Box = (props: any) => (
  <mesh {...props}>
    <meshBasicMaterial attach="material" color="red" />
    <boxGeometry args={[1, 1, 1]} attach="geometry" />
  </mesh>
);

const Composer = ({ active }: any) => {
  const ref = React.useRef();

  return (
    <EffectComposer>
      <Glitch ref={ref} active={active} mode={GlitchMode.CONSTANT_WILD} />
    </EffectComposer>
  );
};

const App = () => {
  const ref = useRef();

  const [selection, select] = useState<Mesh>();
  const [active, activate] = useState<boolean>(true);

  useEffect(() => {
    if (selection) {
      console.log(ref.current);
    }
  }, [selection]);

  return (
    <Fragment>
      <div style={{ background: "#fff" }}>
        <label htmlFor="">Active {JSON.stringify(active)}</label>
        <input
          type="checkbox"
          defaultChecked={active}
          onChange={($event) => {
            activate($event.target.checked);
          }}
        />
      </div>
      <Canvas>
        <Box onClick={(mesh) => select(mesh)} />
        <Composer active={active} />
      </Canvas>
    </Fragment>
  );
};

标签: reactjsthree.jspost-processingreact-three-fiber

解决方案


做就是了

const App = () => {
    ...
    <Canvas>
      <Box .../>
      {active && <Composer/>}
    </Canvas>

const Composer = () => {
  return (
    <EffectComposer>
      <Glitch active={true} mode={GlitchMode.CONSTANT_WILD} />
    </EffectComposer>
  );
};

推荐阅读