相关疑难解决方法(0)

componentDidMount调用BEFORE引用回调

问题

我正在ref使用内联函数定义设置反应

render = () => {
    return (
        <div className="drawer" ref={drawer => this.drawerRef = drawer}>
Run Code Online (Sandbox Code Playgroud)

那么在componentDidMountDOM引用中没有设置

componentDidMount = () => {
    // this.drawerRef is not defined
Run Code Online (Sandbox Code Playgroud)

我的理解是ref应该在mount期间运行回调,但是在ref回调函数之前调用添加console.log语句.componentDidMount

我看过的其他代码示例,例如github上的这个讨论表明了相同的假设,componentDidMount应该在定义的任何回调之后ref调用render,甚至在对话中说明

因此,在执行了所有的ref回调后,componentDidMount被触发了?

是.

我正在使用反应15.4.1

我试过的其他东西

为了验证ref函数被调用,我尝试在类上定义它

setDrawerRef = (drawer) => {
  this.drawerRef = drawer;
}
Run Code Online (Sandbox Code Playgroud)

然后在 render

<div className="drawer" ref={this.setDrawerRef}>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,控制台日志记录显示回调确实在调用之后 componentDidMount

javascript reactjs

71
推荐指数
1
解决办法
2万
查看次数

使用酶测试 `React.createRef` api

我想测试以下使用React.createRefapi 的类。

快速搜索并没有发现任何这样做的例子。有人成功过吗?我将如何嘲笑裁判?

理想情况下,我想使用shallow.

class Main extends React.Component<Props, State> {

  constructor(props) {
    super(props);
    this.state = {
      contentY: 0,
    };

    this.domRef = React.createRef();
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
    handleScroll();
  }

  componentWillUnmount() {
   window.removeEventListener('scroll', this.handleScroll);
  }

  handleScroll = () => {
    const el = this.domRef.current;
    const contentY = el.offsetTop;
    this.setState({ contentY });
  };

  render() {
    return (
      <Wrapper innerRef={this.domRef}>
        <MainRender contentY={this.state.contentY} {...this.props} />
      </Wrapper>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

更新

所以我可以使用回调引用来测试这个,如下所示

 setRef = (ref) => {
   this.domRef = ref;
 } …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs enzyme

7
推荐指数
1
解决办法
7206
查看次数

标签 统计

javascript ×2

reactjs ×2

enzyme ×1

jestjs ×1