【问题标题】:How to properly implement getElementByID in React?如何在 React 中正确实现 getElementByID?
【发布时间】:2021-11-03 12:03:02
【问题描述】:

我试图在 React 中执行 Chart js 函数,但在使用“getElementByID”的每个点都收到错误,即“null 不是对象”。我假设“getElementByID”应该在 React 中以不同的方式格式化,但我无法找到错误的修复方法。有谁知道我将如何格式化以下几行以在 React 中使用?

let mathChart = document.getElementById('mathChart').getContext('2d');
. 
.
document.getElementById("houseTemp").innerHTML = "$" + currentTemp;

它们也在我导入到主 js 文件的函数中,也许我调用它们的方式有问题?

【问题讨论】:

  • 你必须使用 refs 来访问 React 中的 dom 元素
  • 对于反应中的 CharJs 使用 https://github.com/reactjs/react-chartjs
  • 也可以查看 ihttps://stackoverflow.com/questions/32423528/getting-typeerror-document-getelementbyid-is-null-when-using-react-js-wi

标签: javascript html css reactjs react-hooks


【解决方案1】:

你可以通过指定 ref

编辑:在带有函数组件的 react v16.8.0 中,您可以使用 useRef 定义一个 ref。请注意,当您在函数组件上指定 ref 时,您需要在其上使用 React.forwardRef 将 ref 转发到使用 useImperativeHandle 的 DOM 元素以从函数组件中公开某些函数

const Child1 = React.forwardRef((props, ref) => {
return <div ref={ref}>Child1</div>  });

const Child2 = React.forwardRef((props, ref) => {
const handleClick= () =>{};
useImperativeHandle(ref,() => ({
   handleClick
   }))

  return <div>Child2</div> 
 });

 const App = () => {
 const child1 = useRef(null);
 const child2 = useRef(null);

return (
    <>
       <Child1 ref={child1} />
       <Child1 ref={child1} />
    </>
   )
 }

https://reactjs.org/docs/refs-and-the-dom.html

【讨论】:

  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
【解决方案2】:

gcloud 资产导出
--content-type CONTENT_TYPE
--project 'PROJECT_ID'
--snapshot-time 'SNAPSHOT_TIME'
--bigquery-table 'BIGQUERY_TABLE'
--output-bigquery-force

【讨论】:

  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
猜你喜欢
  • 2021-11-03
  • 2022-01-22
  • 1970-01-01
  • 2018-12-07
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 2020-10-11
相关资源
最近更新 更多