Javascript 如何在React中选择DOM元素
当我试图使用'querySelector'或'getElementById'选择DOM元素时 我得到了一个错误:值为null,而document.body工作正常。如果我做错了什么,请告诉我Javascript 如何在React中选择DOM元素,javascript,reactjs,Javascript,Reactjs,当我试图使用'querySelector'或'getElementById'选择DOM元素时 我得到了一个错误:值为null,而document.body工作正常。如果我做错了什么,请告诉我 import React, { Component } from 'react'; import './main.styles.scss'; import { createChart } from 'lightweight-charts'; // const twoC = document.getElem
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;
虽然上面的语句使用的是queryselector,并且getElementById编写正确,但是它们找不到匹配的leElement,因为尚未调用render函数 相反,文档的主体已经定义并呈现,因此它不会返回空值。作为一种解决方法,您可以这样做:
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}
);
}
}
React不能那样工作,您需要使用ref:
你在哪里调用getElementById?如果在调用render方法之前调用它,它将抛出一个错误。您可以尝试在componentDidMount生命周期方法中调用getElementById,该方法在render方法之后调用
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;