首页 > 解决方案 > 如何将反应元素转换为 HTML

问题描述

测试组件的使用

 <TestComponent
   testContent= {
     <div>
       <p>sometxt <a href="#">link1</a><p>
       <p>hello how was your day</p>
       <p>some other txt <a href="#">link1</a><p>
     </div>
   }
 />

class TestComponent extends React.Component {
  constructor(props) {
    const testContent = props.testContent;
  }
}

在上面的组件代码中,在构造函数中,当我尝试访问 props.testContent 时。它的类型是反应元素。但是我想查询内容以找到可聚焦的元素,例如:在这个例子中。由于 prop 值是反应元素 querySelector() 不能使用。所以我需要将此反应元素转换为 HTML 元素。

任何人都可以帮助我知道我该如何实现这一目标。任何帮助是极大的赞赏。

谢谢!

标签: reactjs

解决方案


在您的示例中,还没有 HTML 元素(也称为 DOM 节点) - 在组件安装到 DOM 之前,它不会存在。完成后,您可以使用ReactDOM.findDOMNode()(参见https://reactjs.org/docs/react-dom.html#finddomnode)或ref(参见https://reactjs.org/docs/refs-and-the-dom.html ) 来访问元素。

您需要在React 生命周期方法componentDidMountcomponentDidUpdateReact 生命周期方法中执行此步骤。(见https://reactjs.org/docs/react-component.html#componentdidmount


推荐阅读