javascript - 有条件地禁用父级的子级按钮 - React

标签 javascript reactjs state lifecycle

我有一个 Paginator 子组件,我想禁用左箭头按钮(如果它位于第一页),并使其在第一页上方时再次可单击。与右箭头按钮相同,但页码为 5。

这是我尝试为此解决方案编写的条件:

if (this.state.page <= 1) {
  this.setState({
    disabledPrev: true
  })
} else {
  this.setState({
    disabledPrev: false
  })
}

if (this.state.page >= 5) {
  this.setState({
    disabledNext: true
  })
} else {
  this.setState({
    disabledNext: false
  })
}

但是无论我把它放在哪里,它都不起作用。我认为问题在于生命周期方法的错误使用。

这是完整的代码:

App.js

import React from 'react';
import './App.css';

import Loading from './components/Loading/Loading';
import Header from './components/Header/Header';
import Table from './components/Table/Table';
import Paginator from './components/Paginator/Paginator';

const BASE_URL = 'https://api.udilia.com/coins/v1/'
export default class App extends React.Component{ 
  constructor(props) {
    super(props);
    console.log('constructor');
    this.state = {
      currencies: null,
      isDataReady: false,
      page : 1,
      disabledPrev: false,
      disabledNext: false,
    }
  }

  fetchCurrencies = (pageNumber) => {
    fetch(`${BASE_URL}cryptocurrencies?page=${pageNumber}&perPage=20`)
      .then(res => res.json())
      .then(json => json.currencies)
      .then(currencies => {
        this.setState({
          currencies: currencies,
          isDataReady: true,
        })
      });
  }

  UNSAFE_componentWillMount() {
    console.log('will mount', this.state.page);

  }

  componentDidUpdate() {
    console.log('didUpdate', this.state.page);

  }

  componentDidMount() {
    console.log('did mount', this.state.page);

    //Here is the conditions
    if (this.state.page <= 1) {
      this.setState({
        disabledPrev: true
      })
    } else {
      this.setState({
        disabledPrev: false
      })
    }

    if (this.state.page >= 5) {
      this.setState({
        disabledNext: true
      })
    } else {
      this.setState({
        disabledNext: false
      })
    }

    const {page} = this.state;

    this.fetchCurrencies(page);

  }

  //here is the event handler, I change the page value from here
  handlePaginationClick  = (direction) => () => {
    console.log('clicked', this.state.page);

    let page = direction === 'next' ? this.state.page + 1 : this.state.page - 1;

    this.setState({page})
    this.fetchCurrencies(page);
  }

  render(){
    console.log('render', this.state.page);

    return (
        !this.state.isDataReady
          ? <Loading />
          : <div className="App">
              <Header />
              <Table
                data={this.state.currencies}
              />
              <Paginator 
                prev={this.handlePaginationClick('prev')}
                next={this.handlePaginationClick('next')}
                page={this.state.page}
                disabledPrev={this.state.disabledPrev}
                disabledNext={this.state.disabledNext}
              />

            </div>
    );
  }
}

Paginator.js

import React from 'react';

export default function Paginator(props) {
    return(
        <div>
            <button disabled={props.disabledPrev} onClick={() => props.prev()}> &larr; </button>
            <span>page {props.page} of 10</span>
            <button disabled={props.disabledNext} onClick={() => props.next()}> &rarr; </button>
        </div>
    )
}

最佳答案

您不需要两个状态变量来处理左箭头和右箭头。
将 Paginator 组件修改为如下所示:

import React from "react";

export default function Paginator({ page, min = 1, max = 5 }) {
  return (
    <div>
      <button disabled={page <= min} onClick={() => props.prev()}>
        &larr;
      </button>
      <span>page {props.page} of 10</span>
      <button disabled={page >= max} onClick={() => props.next()}>
        &rarr;
      </button>
    </div>
  );
} 

minmax 值传递给它。

<Paginator
  prev={this.handlePaginationClick("prev")}
  next={this.handlePaginationClick("next")}
  page={this.state.page}
  min={1}
  max={5}
/>

关于javascript - 有条件地禁用父级的子级按钮 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59562165/

相关文章:

javascript - 视频/图像 slider 调整大小以适合屏幕(宽度和高度)

javascript - 为什么 JavaScript 中的不变性如此重要(或需要)?

reactjs - 在 React 中,将获取的 Firebase 数据存储在本地或全局状态中?

variables - 值更改时,如何更新 UIKit 中的 SwiftUI View ?

javascript - 动态改变react-leaflet工具提示的z-index

javascript - React-Redux : Infinite loop when concat to an array in state?

javascript - 加载后如何使用 JavaScript 调整 Google map 的大小?

javascript - 使用 Joi、nodejs 验证 header 参数?

javascript - 如何使用 Javascript 将空格分隔的多行字符串转换为 json?

javascript - 如何使按钮重定向到 React 中的另一个页面