Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 从componentDidMount导出变量_Reactjs - Fatal编程技术网

Reactjs 从componentDidMount导出变量

Reactjs 从componentDidMount导出变量,reactjs,Reactjs,如何从componentDidMount导出“x”变量,以便在渲染部分使用它?我正在检查我的div的x位置 import React from 'react'; class Icon extends React.Component { constructor(props) { super(props); this.selector = React.createRef(); } componentDidMount = () => { var rect

如何从componentDidMount导出“x”变量,以便在渲染部分使用它?我正在检查我的div的x位置

import React from 'react';

class Icon extends React.Component {
  constructor(props) {
    super(props);
    this.selector = React.createRef();
  }

  componentDidMount = () => {
    var rect = this.selector.current.getBoundingClientRect();
    var x = rect.top;
    console.log(x);
   };

  render() {
    return (
      <div className="icon" ref={this.selector}>
        <p>x: {x} & y:</p>
      </div>
    );
  }
}

export default Icon;
从“React”导入React;
类图标扩展了React.Component{
建造师(道具){
超级(道具);
this.selector=React.createRef();
}
componentDidMount=()=>{
var rect=this.selector.current.getBoundingClientRect();
var x=rect.top;
控制台日志(x);
};
render(){
返回(
x:{x}&y:

); } } 导出默认图标;
为什么不使用状态

constructor(props) {
   super(props);
   state = {
      x: null,
   };

   this.selector = React.createRef();
}
然后在生命周期内:

componentDidMount = () => {
   var rect = this.selector.current.getBoundingClientRect();
   this.setState({ x: rect.top });
};
最后是内部渲染:

<p>x: {this.state.x} & y:</p>
x:{this.state.x}&y:


正如他们之前所说,大多数情况下,您希望跟踪正在绘制的数据的状态,如果状态发生变化,让我们做出反应,自动绘制数据的变化

但如果出于任何原因不想跟踪状态,可以使用属性,而不是使用
x
,使用
this.x

import React from 'react';

class Icon extends React.Component {
  constructor(props) {
    super(props);
    this.selector = React.createRef();
  }

  componentDidMount = () => {
    var rect = this.selector.current.getBoundingClientRect();
    this.x = rect.top;
    console.log(this.x);
   };

  render() {
    return (
      <div className="icon" ref={this.selector}>
        <p>x: {this.x} & y:</p>
      </div>
    );
  }
}

export default Icon;
从“React”导入React;
类图标扩展了React.Component{
建造师(道具){
超级(道具);
this.selector=React.createRef();
}
componentDidMount=()=>{
var rect=this.selector.current.getBoundingClientRect();
这个.x=rect.top;
console.log(this.x);
};
render(){
返回(
x:{this.x}&y:

); } } 导出默认图标;