将参数传递给事件处理程序并在ReactJS中获取值?

时间:2018-01-30 14:30:41

标签: reactjs

我已经实现了总共有5页的分页组件。分页是home component的子组件。

当我点击第1页时,它应该通过getpagenumber()handleClick()得到页码,这会使用页码,但是当我们点击页码时,下面的代码getpagenumber()不起作用

pagination.js:

import React, { Component } from 'react';

class Pagination extends Component {

    getpagenumber(val){
        return val;
    }

    handleClick(){
    this.setState({
        end:getpagenumber()*16,
        start:end-16
    });
    const end = getpagenumber()*16;
    this.props.onChange(end - 16, end);
    }

  render() {

    return (
      <div>
        <Content/>
          <div className="container">                 
              <ul className="pagination">
                <li {this.getpagenumber(1)} onClick={this.handleClick}><a href="#">1</a></li>
                <li {this.getpagenumber(2)} onClick={this.handleClick}><a href="#">2</a></li>
                <li {this.getpagenumber(3)} onClick={this.handleClick}><a href="#">3</a></li>
                <li {this.getpagenumber(4)} onClick={this.handleClick}><a href="#">4</a></li>
                <li {this.getpagenumber(5)} onClick={this.handleClick}><a href="#">5</a></li>
              </ul>
          </div>
      </div>
    );
  }
}

export default Pagination;

home.js:

import React, { Component } from 'react';
import Pagination from './pagination';
import Content from './content';

class Home extends Component {
    constructor(props){
        super(props);
        this.state = {
        start:0,
        end:16
        };
    }

    onChangePagination = (start, end) => {
        this.setState({
          start:start,
          end:end
        });
    };

  render() {
    return (
      <div>
          <Content start={start} end={end}/>
          <Pagination onChange={this.onChangePagination}/>
      </div>
    );
  }
}

export default Home;

1 个答案:

答案 0 :(得分:3)

你夸张了一下。所有你需要的是:

import React, { Component } from 'react';

class Pagination extends Component {
    handleClick(value){
      this.setState({
          end: value*16,
          start: end-16
      });
      const end = value*16;
      this.props.onChange(end - 16, end);
    }

  render() {

    return (
      <div>
        <Content/>
          <div className="container">                 
              <ul className="pagination">
                <li><a href="#" onClick={this.handleClick.bind(this, 1)}>1</a></li>
                <li><a href="#" onClick={this.handleClick.bind(this, 2)}>2</a></li>
                <li><a href="#" onClick={this.handleClick.bind(this, 3)}>3</a></li>
                <li><a href="#" onClick={this.handleClick.bind(this, 4)}>4</a></li>
                <li><a href="#" onClick={this.handleClick.bind(this, 5)}>5</a></li>
              </ul>
          </div>
      </div>
    );
  }
}

export default Pagination;

注意:

  • 也许考虑将页数传递给Pagination组件,然后生成一个从1到该数字的数组,然后用点击来映射li。
  • 点击应该在链接标记上。