如何向React自定义Web Components传递Props值?求解决方案
解决React父组件向Web Component子组件传递属性失败的问题
问题原因
React渲染自定义Web Component时,默认会把JSX中的属性作为**DOM属性(property)设置,而react-to-webcomponent包装的Web Component默认从HTML属性(attribute)**中读取props,两者不匹配导致属性无法被正确捕获。
解决方案
方案1:明确指定Web Component监听的属性
修改子组件的react-to-webcomponent配置,通过props选项声明要监听的属性,确保Web Component能正确捕获对应attribute:
import React from 'react'; import reactToWebComponent from "react-to-webcomponent"; const TopDestination = (props) => { console.log(props); return <> <div>{props.name}</div> </> } export default TopDestination // 新增props配置,指定要监听的name属性 customElements.define("top-destination", reactToWebComponent(TopDestination, React, ReactDOM, { props: ['name'] }));
方案2:在React父组件中手动设置HTML属性
利用React的ref和useEffect,手动为Web Component设置HTML属性,确保属性以attribute形式传递:
import { useRef, useEffect } from 'react'; const HelloMessage = (props) => { const destRef = useRef(null); useEffect(() => { if (destRef.current) { // 手动设置HTML attribute destRef.current.setAttribute('name', 'srini'); } }, []); return <> <div className="main-counter" > <top-destination ref={destRef} /> </div> </> } export default HelloMessage customElements.define("react-counter", reactToWebComponent(HelloMessage, React, ReactDOM));
验证
修改后重新运行代码,console.log(props)会正确输出包含name: "srini"的对象,子组件也能正常渲染该值。
内容的提问来源于stack exchange,提问作者Srinivasan
相关产品推荐
相关产品推荐

