[英]How to select a DOM element in React
當我嘗試使用'querySelector'
或'getElementById'
到 select 一個 DOM 元素時,我收到Error: Value is null
與document.body
工作得很好。 如果我做錯了什么,請告訴我。
import React, { Component } from 'react';
import './main.styles.scss';
import { createChart } from 'lightweight-charts';
// const twoC = document.getElementById('twoCharts');
// const twoC = document.querySelector('.twoC');
// const body = document.body;
const twoC = document.querySelector('#twoCharts');
const chart = createChart(twoC, {
width: 1200,
height: 600,
});
class Main extends Component {
render() {
return (
<div className="main">
<div className="trading">
<div className="box one">1</div>
<div className="box twoC" id="twoCharts"></div>
</div>
<div className="charts">
<div className="box three">3</div>
<div className="box four">4</div>
</div>
</div>
);
}
}
export default Main;
React 不能那樣工作,你需要使用參考: https://reactjs.org/docs/refs-and-the-dom.html
import React, { Component, createRef } from 'react';
import './main.styles.scss';
import { createChart } from 'lightweight-charts';
const chart = createChart(twoC, {
width: 1200,
height: 600,
});
class Main extends Component {
// Create the ref
ref = createRef();
componentDidMount() {
// After the first render
console.log(this.ref.current); // Gets the current HTML element thats rendered
}
render() {
return (
<div className="main">
<div className="trading">
<div className="box one">1</div>
// Set the ref on this element
<div className="box twoC" id="twoCharts" ref={this.ref}></div>
</div>
<div className="charts">
<div className="box three">3</div>
<div className="box four">4</div>
</div>
</div>
);
}
}
export default Main;
雖然您上面的語句使用queryselector
並且getElementById
編寫正確,但它們無法找到匹配的 lelement,因為尚未調用渲染 function。
相反,文檔的主體已經定義和渲染,因此它不會返回null
值。 作為一種解決方法,您可以這樣做:
import React, { Component } from 'react';
import './main.styles.scss';
import { createChart } from 'lightweight-charts';
const body = document.body;
const chart = createChart(body, {
width: 1200,
height: 600,
});
class Main extends Component {
const one,two,three;
getElements = () => {
this.one = document.getElementById('twoCharts');
this.two = document.querySelector('.twoC');
this.three = document.querySelector('#twoCharts');
//do something
}
render() {
return (
<div className="main">
<div className="trading">
<div className="box one">1</div>
<div className="box twoC" id="twoCharts"></div>
</div>
<div className="charts">
<div className="box three">3</div>
<div className="box four">4</div>
</div>
</div>
{this.getElements}
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.