我可以在渲染中使用引用吗?

Yichaoz

以下代码显然不起作用,但是我的想法是,我想根据子组件的clientHeight进行条件渲染,不确定是否可能

class App extends Component {
  constructor() {
    super();
    this.comp = {};
    this.state = {
      clientHeight: 0
    };
  }

  componentDidMount() {
    console.log(this.comp)
    this.setState({
      clientHeight: this.comp.clientHeight
    });
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} ref={comp => this.comp = comp}/>
        {
          this.state.clientHeight > 100 ? <ComponentA /> : <ComponentB />
        }
      </div>
    );
  }
}
Yichaoz

事实证明,@ Dane的想法帮助了我。componentDidUpdate钩。这个实现器是我想要的,但是它每次渲染两次,一次分配给ref,然后将更新更改为新的clientHeight,然后根据新的clientHeight再次渲染。不知道是否有更好的方法。

class App extends Component {
  constructor() {
    super();
    this.comp = {};
    this.state = {
      clientHeight: 0
    };
  }

  componentDidUpdate(prevProps){
      if(prevProps !== this.props){
        this.setState({
          clientHeight: this.comp.clientHeight
        })
      }
    } 

  render() {
    return (
      <div>
        <Hello name={this.state.name} ref={comp => this.comp = comp}/>
        {
          this.state.clientHeight > 100 ? <ComponentA /> : <ComponentB />
        }
      </div>
    );
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我可以在.vue文件中使用渲染功能吗

我可以在非渲染组件中使用use *函数(useState,useRef,useContext)吗?

我可以在iSwing应用程序中使用iText渲染PDF吗?

我可以在React中使用多个布尔值进行条件渲染吗?

我可以在 reactstrap 的渲染中使用 useEffect 中声明的变量吗?

我可以在HTML文件中使用javascript库代码代替引用它吗?

我们可以在C#中使用Struct作为引用类型吗?

我可以在HTML中使用变量吗?

我可以在匹配中使用“ <”和“>”吗?

我可以在AnyObject中使用元组吗?

我可以在PureComponent中使用shouldComponentUpdate吗

我可以在查询中使用Mutators吗?

我可以在JTA中使用Hibernate吗?

我可以在DrawerLayout中使用SwipeRefreshLayout吗?

我可以在ARC中使用retain吗?

我可以在 <urlset> 中使用 <sitemap> 吗?

我可以在PowerShell中使用“ &&”或“ -and”吗?

我可以在cgo中使用c ++吗?

我可以在UIScrollView中使用UIRefreshControl吗?

我可以在ArrayFire中使用广播吗?

我可以在TideSDK中使用webrtc吗?

我可以在deinit中使用didSet吗?

我可以在TFVC中使用.gitignore吗?

我可以在php中使用php吗

我可以在C ++中使用Tk吗?

我可以在 switch 中使用 .map() 吗?

我可以在构造函数中使用 for 吗?

您可以在@PreAuthorize中使用SpEL引用实例属性吗?

我们可以在Java中使用按引用传递吗?如果否,java.util.Arrays.sort如何工作?