将动态参数传递给事件处理程序

时间:2018-01-27 13:50:24

标签: javascript reactjs

您好我想将动态参数传递给点击处理程序。 ClassResult进行ajax调用并获取结果数组,然后我将道具传递给另一个组件StudentResult。现在我想在点击事件处理程序中获得这些道具。

代码:

class ClassResult extends Component {

   constructor(props) {
     super(props);
     this.state = {terminal: 'Select Terminal', class : 'Select Class'};
     this.state = {
        result: []
   };

 return(){
    render(
         {this.state.result.map((post, i) =><StudentResult key={i} name={post.STDNAME} roll={post.STROLLNO} om={post.STDTOTALOM} division={post.STDDIVGRADE} percent={post.STPERCENTAGE} remarks={post.STREMAKRS} schoolid={post.SCHOOLID} regno={post.REGNO}/>)}

  }
}


class StudentResult extends Component {

   constructor(props) {
    super(props);
    axios.defaults.baseURL = 'http://localhost:8000/api';
    this.state = {fail : ''};
    this.displayDetailResult = this.displayDetailResult.bind(this, schoolid, regno);
   }

   displayDetailResult(e, schoolid, regno){
     //How to get schoolid and regno here

     alert(schoolid);
   }

   render() {
     if(this.props.percent < 50) {
              this.setState({fail : 'table-danger'});
            } else {
                this.setState({fail : ''});
            } 
  return (


            <tr className={this.state.fail} onClick={(e) => this.displayDetailResult(e, this.prop.schoolid, this.prop.regno)}>
                <td>{ this.props.name }</td>
                <td>{ this.props.roll }</td>
                <td>{ this.props.om }</td>
                <td>{ this.props.division }</td>
                <td>{ this.props.percent }</td>
                <td>{ this.props.remarks }</td>
            </tr>

  )
}

1 个答案:

答案 0 :(得分:1)

问题在于您在构造函数中绑定displayDetailResult的方式。

你写过

this.displayDetailResult = this.displayDetailResult.bind(this, schoolid, regno);

且henere schoolidregno不可用,

你只需要写

this.displayDetailResult = this.displayDetailResult.bind(this);

称之为

<tr className={this.state.fail} onClick={this.displayDetailResult}>

然后在displayDetailResult函数中你将有

displayDetailResult(e){
     console.log(this.props.schoolid, this.props.regno)
   }