Javascript 在React JS中单击时禁用按钮

Javascript 在React JS中单击时禁用按钮,javascript,reactjs,Javascript,Reactjs,我试图在React JS中禁用单击按钮,因为它的功能是向数组中添加文章。当用户单击“保存文章”时,该按钮应禁用,这样他们就无法再次保存 到目前为止,对于该组件,我的代码如下: import React, { Component } from 'react'; import './news-hero.css'; import Carousel from "react-multi-carousel"; import "react-multi-carousel/lib/styles.css"; co

我试图在React JS中禁用单击按钮,因为它的功能是向数组中添加文章。当用户单击“保存文章”时,该按钮应禁用,这样他们就无法再次保存

到目前为止,对于该组件,我的代码如下:

import React, { Component } from 'react';
import './news-hero.css';
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";

const responsive = {
    superLargeDesktop: {
        breakpoint: { max: 4000, min: 3000 },
        items: 1,
    },
    desktop: {
        breakpoint: { max: 3000, min: 1024 },
        items: 1,
    },
    tablet: {
        breakpoint: { max: 1024, min: 464 },
        items: 1,
    },
    mobile: {
        breakpoint: { max: 464, min: 0 },
        items: 1,
    },
};

class NewsHero extends Component {
    _isMounted = false;
    state = {
        loading: false,
        data: [],
        headline: [],
        saved: []
    }

    saved = headline => {
        this.setState(
            (prevState) => ({ saved: [...prevState.saved, headline] }),
            () => {
                console.log('Saved articles = ', this.state.saved);
                alert('Article saved');
                localStorage.setItem('saved', JSON.stringify(this.state.saved));
                localStorage.getItem('saved');
            });
    }

    constructor(props) {
        super(props)
        this.saved = this.saved.bind(this)
    }

    onError() {
        this.setState({
            imageUrl: "../assets/img-error.jpg"
        })
    }

    componentDidMount() {
        this._isMounted = true;
        this.setState({ loading: true, saved: localStorage.getItem('saved') ? JSON.parse(localStorage.getItem('saved')) : [] })
        fetch('https://newsapi.org/v2/everything?q=timbaland&domains=rollingstone.com,billboard.com&excludeDomains=townsquare.media&apiKey=xxxx')
            .then(headline => headline.json())
            .then(headline => this.setState({ headline: headline.articles, loading: false }, () => console.log(headline.articles)))
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    render() {
        return (
            <div className="hero">
                <h2 className="text-left">News</h2>

                {this.state.loading
                    ? "loading..."
                    : <div>
                        <Carousel
                            additionalTransfrom={0}
                            showDots={true}
                            arrows={true}
                            autoPlaySpeed={3000}
                            autoPlay={false}
                            centerMode={false}
                            className="carousel-hero"
                            containerClass="container-with-dots"
                            dotListClass="dots"
                            draggable
                            focusOnSelect={false}
                            infinite
                            itemClass="carousel-top"
                            keyBoardControl
                            minimumTouchDrag={80}
                            renderButtonGroupOutside={false}
                            renderDotsOutside
                            responsive={responsive}>
                            {this.state.headline.map((post, indx) => {
                                return (
                                    <div className="text-left mt-5" key={indx}>
                                        <img className="media-img card-img-top card-img-hero" src={post.urlToImage} alt="Alt text"></img>
                                        <div className="card-body container hero-text-body">
                                            <h1 className="card-title hero-title text-truncate">{post.title}</h1>
                                            <button className="btn-primary btn mt-2 mb-4" onClick={() => this.saved(post)}>Save article</button>
                                            <p className="card-text">{post.description}</p>
                                            <a href={post.url} target="_blank" rel="noopener noreferrer">Read More</a>
                                        </div>
                                    </div>
                                )
                            })}
                        </Carousel>
                    </div>
                }
            </div>
        )
    }
}
export default NewsHero;
import React,{Component}来自'React';
导入“/news hero.css”;
从“react multi Carousel”导入转盘;
导入“react multi carousel/lib/styles.css”;
常数响应={
超大桌面:{
断点:{max:4000,min:3000},
项目:1,
},
桌面:{
断点:{max:3000,min:1024},
项目:1,
},
平板电脑:{
断点:{max:1024,min:464},
项目:1,
},
流动电话:{
断点:{max:464,min:0},
项目:1,
},
};
类NewsHero扩展组件{
_isMounted=错误;
状态={
加载:false,
数据:[],
标题:[],
已保存:[]
}
已保存=标题=>{
这是我的国家(
(prevState)=>({saved:[…prevState.saved,headline]}),
() => {
console.log('Saved articles=',this.state.Saved);
警报(“物品已保存”);
localStorage.setItem('saved',JSON.stringify(this.state.saved));
localStorage.getItem('saved');
});
}
建造师(道具){
超级(道具)
this.saved=this.saved.bind(this)
}
onError(){
这是我的国家({
imageUrl:“../assets/img error.jpg”
})
}
componentDidMount(){
这个。_isMounted=true;
this.setState({加载:true,保存:localStorage.getItem('saved')?JSON.parse(localStorage.getItem('saved')):[]))
取('https://newsapi.org/v2/everything?q=timbaland&domains=rollingstone.com,billboard.com&excludeddomains=townsquare.media&apiKey=xxxx')
.then(headline=>headline.json())
.then(headline=>this.setState({headline:headline.articles,load:false},()=>console.log(headline.articles)))
}
组件将卸载(){
这个。_isMounted=false;
}
render(){
返回(
新闻
{this.state.loading
“装载…”
: 
{this.state.headline.map((post,indx)=>{
返回(
{post.title}
this.saved(post)}>保存文章

{post.description}

) })} } ) } } 导出默认新闻英雄;

其他问题的答案并不能真正回答这个直截了当的问题,因为其他问题是针对其他场景代码的定制答案

您可以将事件传递给
onClick()
函数

onClick={(e) => this.saved(e, post)}
然后可以使用该事件和
currentTarget
获取包含
onClick
的HTML元素并禁用该元素

saved = (e, headline) => {
    // Disable clicked button
    e.currentTarget.disabled = true;
    ...
}

正如Ed Lucas所建议的,您可以这样做,或者,您可以在状态上保持按钮状态,并根据单击事件进行更改

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {
  constructor() {
    super();
    this.state = {
      btnStatus: false
    };
  }

  render() {
    return (
      <div>
        <button 
          disabled={this.state.btnStatus}
          onClick={() => this.setState({ btnStatus: true })}
        >
          CLICK
        </button>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
import React,{Component}来自'React';
从'react dom'导入{render};
类应用程序扩展组件{
构造函数(){
超级();
此.state={
btnStatus:错误
};
}
render(){
返回(
this.setState({btnStatus:true})
>
点击
);
}
}
render(,document.getElementById('root'));

将禁用的道具添加到按钮并保存一些状态,以确定按钮是否禁用。然后在单击时设置该状态。确定。。。你有代码样本吗