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

Hay*_*Ali 0 reactjs react-dom

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;
Run Code Online (Sandbox Code Playgroud)

这是我的代码,我的 .length 方法返回 0,而有 3 个 div 使用我在 React 中开始的同一个类,所以我可能在某个地方出错

Rya*_* Le 5

您的代码在渲染之前运行,因此不会渲染任何元素

将其移动到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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)