我的.length方法返回0时,我有9 div在reactjs


const boxes = {
height: 220,
width: 220,
backgroundColor: 'red',
borderRadius: '25%',
};
const main = {
display: 'grid',
gridTemplateColumns: 'auto auto auto',
gridGap: '20px',
justifyContent: 'center',
marginTop: '20px',
};
const box = document.querySelectorAll('.boxes');
console.log(box.length);
class Easy extends React.Component {
render() {
return (
<div className="easy-game">
<div className="Easy-main" style={main}>
<div style={boxes} className="boxes" />
<div style={boxes} className="boxes" />
<div style={boxes} className="boxes" />
</div>
</div>
);
}
}
export default Easy;

这是我的代码和我的。length方法给出0的回报,而有3div使用相同的类,我开始在反应,所以我可能是错误的地方

您的代码在渲染之前运行,因此将没有元素呈现

将其移动到初始渲染后运行的componentDidMount中:

class Easy extends React.Component {
componentDidMount() {
const box = document.querySelectorAll('.boxes');  //<-- Move it here
console.log(box.length);
}
render() {
return (
<div className="easy-game">
<div className="Easy-main" style={main}>
<div style={boxes} className="boxes" />
<div style={boxes} className="boxes" />
<div style={boxes} className="boxes" />
</div>
</div>
);
}
}