【问题标题】:Component's JavaScript doesn't execute on routing with React router组件的 JavaScript 不会在使用 React 路由器的路由上执行
【发布时间】:2019-01-31 03:42:42
【问题描述】:

我正在开发我的第一个 React 项目。我需要用 JS 对某些部分进行样式设置,因为我依赖于内容。我在 JQuery 的 $(document).ready() 上从组件 componentDidMount() 调用 JS 函数,否则它将找不到要设置样式的节点。

当我进入页面或刷新样式时按计划工作,但是当我使用路由器的<Link><NavLink> 时,JS 不会加载。

有没有办法让它工作?

class About extends React.Component {
  constructor() {
    super();
  }

  componentDidMount() {
      $(document).ready( function () {
        indentation($('.page__content__career').children(), 85);
        indentation($('.page__about .page__content__text').children(), 100);
      });

  }

  render() {
    return (
      <div className="page page__about">
        <div className="page__content page__about__content">
          <h1>about</h1>
          <hr />
          <div className="page__content__photo">
            <img src={'../images/profile-picture-square--dark.jpg'} />
          </div>
          <div className="page__content__text">
            <p>Hello, World</p>
          </div>
          <ul className="page__content__career">
            {
              cvList.map( (job) => {
                return (
                  <CVElement
                    startTime={job.startTime}
                    endTime={job.endTime}
                    description={job.description}
                    place={job.place}
                    link={job.link}
                  />
                )
              })
            }
          </ul>
        </div>
      </div>
    );
  }
}


export default About;

我也试过在进入的时候调用尊敬的函数,还是不行

    <Route path="/en/about" component={About} onEnter={() => console.log('Entered About')}/>

【问题讨论】:

    标签: javascript jquery reactjs react-router components


    【解决方案1】:

    好的,我发现了。其实很简单。正如@Alex Dovzhanyn 建议的那样,我摆脱了 jQuery,但随后使用了 DOM 样式对象。

    componentDidMount() {
    
          const pageAboutChildren = document.querySelector('.page__about .page__content__text').childNodes;
          const pageAboutCareer = document.querySelector('.page__content__career').childNodes;
    
          indentation(pageAboutChildren, 100);
          indentation(pageAboutCareer, 85);
          changeColor();
      }
    

    indentation() 是:

    const indentation = (element, indent) => {
      for(var i = 0; i < element.length; i++) {
        element[i].style.marginLeft =  indent * (i+1) + 'px';
      }
    
    }
    

    我遇到了一些引用问题,这让我更加困惑 毕竟没那么难

    【讨论】:

      【解决方案2】:

      为什么要使用 jQuery 来设置样式?为什么要使用 jQuery?只需使用 style={{}} 属性将您的样式传递给适当的元素,如下所示:

      <ul className="page__content__career" style={{ marginLeft: '100px' }}>
        ...
      </ul>
      

      【讨论】:

      • 我必须遍历元素并根据索引为每个元素设置样式。我使用 jQuery 是出于习惯,我可以摆脱它,但无论如何我都需要一个函数
      猜你喜欢
      • 2021-09-26
      • 2019-03-27
      • 2021-10-09
      • 2016-04-28
      • 2019-11-13
      • 2018-12-12
      • 1970-01-01
      • 2018-01-20
      • 2018-12-31
      相关资源
      最近更新 更多