ReactJS。如何获取组件内部元素的状态

ReactJS。如何获取组件内部元素的状态,reactjs,Reactjs,请帮助我获取react组件内的元素状态或其他一些自定义功能以及我需要的信息。每个td标签都包含react组件Block1。 下面是简化的代码结构 class Block2 extends React.Component { render() { return ( <table> <tbody> <tr> <td> <Block1 />

请帮助我获取react组件内的元素状态或其他一些自定义功能以及我需要的信息。每个td标签都包含react组件Block1。 下面是简化的代码结构

class Block2 extends React.Component {
render() {
  return (
    <table>
      <tbody>
        <tr>
          <td>
            <Block1 />
          </td>
          <td>
            <Block1 />
          </td>
        </tr>
      </tbody>
    </table>
  )}}
class Block2扩展了React.Component{
render(){
返回(
)}}
Block1-包含div元素的react组件。 块2位于组件块3内。如何通过单击某个按钮从Block3获取Block1的状态?
现在,我可以得到Block1列表,可以看到道具,但看不到状态。或者我可以获取DOM td元素并查看子类名称(我在状态中查找),但我看不到道具…

除非您使用Redux之类的库,否则您必须执行以下操作来解决您的问题:
将状态存储在
块3
中,而不是
块1
中。然后将任何将此状态更改为
props
的函数从
Block3
传递到
Block2
Block1
。当
块1中发生任何更改时,调用此函数。模式应为:

class Block3 {
  changeState(value) {
    this.setState({ stateValue: value });
  }
  render() {
    return (
      <Block2 changeState={this.changeState}/>
    )
  }
}

class Block2 extends React.Component {
render() {
  return (
    <table>
      <tbody>
        <tr>
          <td>
            <Block1 changeState={this.props.changeState} />
          </td>
          <td>
            <Block1 changeState={this.props.changeState} />
          </td>
        </tr>
      </tbody>
    </table>
  )}}


class Block1 {
  changeHandler(ev) {
    this.props.changeState(ev.target.value);
  }
  render() {
    return (
      <button onClick={this.changeHandler}/>
    )
  }
}
编辑:查看代码后的我的解决方案:

import React, { Component } from 'react';
import './Hall.css';

class HallCol extends Component {
    constructor(props) {
      super(props);
      this.state = {
        chair_cls:'chair-default'
      };
      this.handleClick = this.handleClick.bind(this);
    }

    handleClick(e) {
      let chair_cls = null;
      if(this.state.chair_cls==="chair-default") {
        chair_cls = 'chair-sold';
        this.props.updateCount(1, this.props.seat_number);
      } else {
        chair_cls = 'chair-default';
        this.props.updateCount(-1, this.props.seat_number);
      }

      this.setState({
        chair_cls: chair_cls
      });
    }

    render(){
      return(
            <div className={this.state.chair_cls} onClick={this.handleClick}>
              <div className="backrest">
                  <p>{this.props.seat_number}</p>
              </div>
              <div className="armrest-left">
              </div>
              <div className="armrest-right">
              </div>
            </div>
        );
    }
}

class Table extends React.Component {
  constructor() {
    super();
    this.genRow = this.genRow.bind(this);         // this is method binding
  }

  genRow() {
    var rows = this.props.rows;
    return rows.map(function(v, i) {
      var tmp = v.map(function(v2, j) {
        return (
          <td key={'td' + i + '_' + j} className='chair-cell' >
            {v2}
          </td>
        );
      });

      return (
        <tr key={'tr' + i}>
          {tmp}
        </tr>
      )
    });
  }

  render() {
    return (
      <table className="hall-grid" >
        <tbody>
          {this.genRow()}
        </tbody>
      </table>
    );
  }
}

class Hall extends React.Component {
  constructor(props) {
    super(props);
    var rows_num = this.props.rows;
    var cols_num = this.props.cols;

    this.AddRow = this.AddRow.bind(this);
    this.updateSeats = this.updateSeats.bind(this);

    var row = [];
    for (var i = 0; i < rows_num; i++) {
      var col = [];
      for (var k = 0; k< cols_num; k++) {
          col.push(<HallCol row = {i+1} seat_number = {k+1} updateCount={this.updateSeats} />);  // bind the passed function to parent
      }
      row.push(col);
    }
    this.state = {
      rows: row,
      bookedSeats: [],
      count: 0
    };
  }

  AddRow() {
    let newRows = this.state.rows;
    newRows.push([0, 0]);
    this.setState({rows: newRows});
  }
  updateSeats(val, seat_number) {
    let bookedSeatsUpdated;
    if( val === 1 ) {
      bookedSeatsUpdated = this.state.bookedSeats.concat(seat_number);
    } else {
      bookedSeatsUpdated = this.state.bookedSeats;
      let index = bookedSeatsUpdated.indexOf(seat_number);
      bookedSeatsUpdated.splice(index,1);
    }
    this.setState({
      bookedSeats: bookedSeatsUpdated,
      count: this.state.count + val
    });
  }

  render() {
    return (
      <div className="hall">
        <Table rows={this.state.rows} />
        <button className = "btn-default" onClick={() => {
            alert(this.state.count + 'seats : ' + this.state.bookedSeats);
          } }>
            TOTAL SOLD
        </button>
      </div>
    );
  }
}

export default Hall;
import React,{Component}来自'React';
导入“/Hall.css”;
类扩展组件{
建造师(道具){
超级(道具);
此.state={
主席(cls):“主席-默认”
};
this.handleClick=this.handleClick.bind(this);
}
handleClick(e){
设chair_cls=null;
if(this.state.chair_cls==“chair default”){
椅子_cls=‘出售的椅子’;
this.props.updateCount(1,this.props.seat_编号);
}否则{
主席_cls=‘主席默认值’;
this.props.updateCount(-1,this.props.seat_number);
}
这是我的国家({
主席:主席
});
}
render(){
返回(
{这个.道具.座位号}

); } } 类表扩展了React.Component{ 构造函数(){ 超级(); this.genRow=this.genRow.bind(this);//这是方法绑定 } genRow(){ var rows=this.props.rows; 返回rows.map(函数(v,i){ var tmp=v.map(函数(v2,j){ 返回( {v2} ); }); 返回( {tmp} ) }); } render(){ 返回( {this.genRow()} ); } } 类。组件{ 建造师(道具){ 超级(道具); var rows_num=this.props.rows; var cols_num=this.props.cols; this.AddRow=this.AddRow.bind(this); this.updateSeats=this.updateSeats.bind(this); var行=[]; 对于(变量i=0;i 销售总额 ); } } 导出默认大厅;
您的意思是想在子组件中访问父组件的状态吗?请参阅更新的回答非常感谢您的回答!我只想访问子状态。我尝试按照您的建议设置引用,但只能获取一个组件的状态。如何获取所有组件的状态?Block1我放入表
code
var行=[];for(var i=0;i);}row.push(col);}this.state={rows:row}
code
并尝试获取状态
code
countsell(e){this.state.rows.map(函数(row){row.map(函数(col){console.log(col);});}render(){return(this.countsell(this)}>TOTAL sell);}
code
我说过可以使用
refs
,但它已被弃用。对于您的代码,在我的答案中以
props
like的形式传递函数就足够了。如果你在这方面遇到任何问题,让我知道我明白了你的想法,并尝试了十几次来实现这一点。但我刚刚开始研究React,很可能没有在代码中正确描述组件的结构。如果您在我最后一次尝试时看到Git上的真实代码,我将非常感激。我认识了Redux,我确信这正是我所需要的!再次感谢您的建议!
import React, { Component } from 'react';
import './Hall.css';

class HallCol extends Component {
    constructor(props) {
      super(props);
      this.state = {
        chair_cls:'chair-default'
      };
      this.handleClick = this.handleClick.bind(this);
    }

    handleClick(e) {
      let chair_cls = null;
      if(this.state.chair_cls==="chair-default") {
        chair_cls = 'chair-sold';
        this.props.updateCount(1, this.props.seat_number);
      } else {
        chair_cls = 'chair-default';
        this.props.updateCount(-1, this.props.seat_number);
      }

      this.setState({
        chair_cls: chair_cls
      });
    }

    render(){
      return(
            <div className={this.state.chair_cls} onClick={this.handleClick}>
              <div className="backrest">
                  <p>{this.props.seat_number}</p>
              </div>
              <div className="armrest-left">
              </div>
              <div className="armrest-right">
              </div>
            </div>
        );
    }
}

class Table extends React.Component {
  constructor() {
    super();
    this.genRow = this.genRow.bind(this);         // this is method binding
  }

  genRow() {
    var rows = this.props.rows;
    return rows.map(function(v, i) {
      var tmp = v.map(function(v2, j) {
        return (
          <td key={'td' + i + '_' + j} className='chair-cell' >
            {v2}
          </td>
        );
      });

      return (
        <tr key={'tr' + i}>
          {tmp}
        </tr>
      )
    });
  }

  render() {
    return (
      <table className="hall-grid" >
        <tbody>
          {this.genRow()}
        </tbody>
      </table>
    );
  }
}

class Hall extends React.Component {
  constructor(props) {
    super(props);
    var rows_num = this.props.rows;
    var cols_num = this.props.cols;

    this.AddRow = this.AddRow.bind(this);
    this.updateSeats = this.updateSeats.bind(this);

    var row = [];
    for (var i = 0; i < rows_num; i++) {
      var col = [];
      for (var k = 0; k< cols_num; k++) {
          col.push(<HallCol row = {i+1} seat_number = {k+1} updateCount={this.updateSeats} />);  // bind the passed function to parent
      }
      row.push(col);
    }
    this.state = {
      rows: row,
      bookedSeats: [],
      count: 0
    };
  }

  AddRow() {
    let newRows = this.state.rows;
    newRows.push([0, 0]);
    this.setState({rows: newRows});
  }
  updateSeats(val, seat_number) {
    let bookedSeatsUpdated;
    if( val === 1 ) {
      bookedSeatsUpdated = this.state.bookedSeats.concat(seat_number);
    } else {
      bookedSeatsUpdated = this.state.bookedSeats;
      let index = bookedSeatsUpdated.indexOf(seat_number);
      bookedSeatsUpdated.splice(index,1);
    }
    this.setState({
      bookedSeats: bookedSeatsUpdated,
      count: this.state.count + val
    });
  }

  render() {
    return (
      <div className="hall">
        <Table rows={this.state.rows} />
        <button className = "btn-default" onClick={() => {
            alert(this.state.count + 'seats : ' + this.state.bookedSeats);
          } }>
            TOTAL SOLD
        </button>
      </div>
    );
  }
}

export default Hall;