reactjs - 如何将反应元素转换为 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 元素。
任何人都可以帮助我知道我该如何实现这一目标。任何帮助是极大的赞赏。
谢谢!
解决方案
在您的示例中,还没有 HTML 元素(也称为 DOM 节点) - 在组件安装到 DOM 之前,它不会存在。完成后,您可以使用ReactDOM.findDOMNode()
(参见https://reactjs.org/docs/react-dom.html#finddomnode)或ref
(参见https://reactjs.org/docs/refs-and-the-dom.html ) 来访问元素。
您需要在React 生命周期方法componentDidMount
或componentDidUpdate
React 生命周期方法中执行此步骤。(见https://reactjs.org/docs/react-component.html#componentdidmount)
推荐阅读
- node.js - 如何在插座上踢别人
- python - 如何使用python从多个json文件中提取信息
- animation - iOS15 / iPhone12 setContentOffset 动画问题
- html - 如何根据用户搜索的内容显示结果 django
- google-sheets - 根据另一个单元格中提供的计数重复一个值 - Google 表格
- c# - 在 C# 中运行的所有 if 语句?
- reactjs - 如何从连接到 Firebase 的 DataGrid 中删除一行?
- javascript - 拖放在移动视图中不起作用
- entity-framework - 如何清理使用的实体框架库
- node.js - Chai.js 不在同步编译器块中运行代码