如何渲染每次三个元素?应对

时间:2018-03-30 01:39:24

标签: reactjs

我希望每次只渲染数组numbers的三个元素。

每次我点击em next来更改数字。

e.g: 在屏幕上:123,我点击按钮,将出现,456及以后。

mycode的:



class Contador extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      elementsPerPage:3,
      currentPage:0,
      numbers:[1,2,3,4,5,6,7,8,9,10]
    };

    this.nextPage = this.nextPage.bind(this);
  }
  
  nextPage () {
   this.setState({ currentPage: this.state.currentPage + 1 });
    console.log(this.state.currentPage)  
  }
  
  elementsOnScreen () {
    this.state.numbers.map((number)=>
      <li>{number}</li>)
  }
  
  render() {
    return (
      <div>
        <h1>Elements: {this.elementsOnScreen} </h1>
      <h1>Current Page: {this.state.currentPage}</h1>
      <button onClick={this.nextPage}> next </button>
        </div>
    );
  }
}

ReactDOM.render(
<Contador/>,
  document.getElementById('root')
)
&#13;
<div id="root"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以使用Array.prototype.slice()

elementsOnScreen () {
  const { currentPage, numbers, elementsPerPage } = this.state;
  return numbers
    .slice(currentPage*elementsPerPage, currentPage*elementsPerPage + elementsPerPage + 1)
    .map(number => (<li>{number}</li>));
}

答案 1 :(得分:0)

使用切片方法从this.state.numbers中提取三个元素,并使用map函数映射它们。

elementsOnScreen () {
 const { currentPage, numbers, elementsPerPage } = this.state;
 return numbers
  .slice(currentPage*elementsPerPage, currentPage*elementsPerPage + elementsPerPage)
  .map(number => (<li>{number}</li>));
}

另外,当你在jsx中渲染一个函数时,你必须调用该函数而不传递它的值

<h1>Elements: {this.elementsOnScreen()} </h1>  

this.elementsOnScreen将传递该函数,它不会运行该函数。要运行该函数并返回其值,您必须执行this.elementsOnScreen()