简体   繁体   中英

Blazor Custom Elements - is two-way binding and hook to EventCallback possible in React?

I have a Blazor component with two-way binding and additional EventCallback property. All works fine when I consume such component in Blazor. However, I'd like to reuse same component as Custom Element (web component) in React or Angular.

Here is what I tried for hooking to EventCallback:

Blazor side:

[Parameter]
public EventCallback<(long, string)> MessageReceived { get; set; }

React

function App() {

  const notificationElement = useRef();

  function messageReceivedListener(message){
    console.log(message);
  }

  useEffect( () => {
    notificationElement.current.addEventListener('message-received', messageReceivedListener);

    return () => {
      notificationElement.current.removeEventListener('message-received', messageReceivedListener);
    }
  });

  return (
    <div className="App">
          <notification-component ref={notificationElement}>
          </notification-component>
    </div>
  );
}

Even though I'm positive that Blazor component invoke MessageReceived event, I was unable to receive it in React code.

In this approach of 2 different web technologies what I advise you is to use Custom Events

https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events

Where from Blazor you fire an event (using JSInterop) and from a React component you listen for it.

It would also work the other way around.

I hope Microsoft releases a more direct solution for communication between Blazor with React

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM