8000 [Article] How to write custom event listener for C# changes in React · Issue #8 · ReactUnity/reactunity.github.io · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content 8000
[Article] How to write custom event listener for C# changes in React #8
Open
@Muchaszewski

Description

@Muchaszewski

Example code to put in the article

C#

    public Action AddKeyPressListener(object callback)
    {
        var cb = ReactUnity.Helpers.Callback.From(callback);
        Action<string> listener = null;
        listener = (val) => {
            if (cb?.callback == null) // Check if we lost reference to cb, if so unsubscribe because we probably lost handle.
            {
               OnKeyPress  -= listener;
               return;
            }
            cb.Call(val);
        }

        OnKeyPress += listener;

        return () => OnKeyPress -= listener;
    }

TSX

  const [key, setKey] = useState("");
  useEffect(() => {    
    const unsubscribe = Global.Instance.AddKeyPressListener((input: string) => {
      setKey(input);
    });
    // Get current value before hook is called
    const input= Global.Instance.LastKeyPressed;
    setKey(input);
    return () => unsubscribe();
  }, []);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0