簡體   English   中英

單擊后如何在按鈕數組中禁用特定按鈕?

[英]How can I disable a particular button after click, in a buttons array?

我的問題是,如何根據單擊來禁用Button數組中的特定按鈕? 在下面有一個SearchField組件,其中包含多個按鈕,我只想禁用單擊的按鈕,但是所有按鈕都變為禁用,我該如何解決?

 state = {
        redirect: false,
        loading: false,
        alreadyAddedFav: false,
        disabled: false
    }




onClickedHandler = (recipe_id, token) => {
        if (!this.props.isAuthenticated) {
            this.setState({ redirect: true })
        }
        else {
            const favData = {
                recipe_id: recipe_id,
                userId: this.props.userId
            }
            if (this.props.favRecipes.length > 0) {

                if (!this.props.favRecipes.some(item => item.recipe_id === recipe_id)) {

                    console.log("added in the loop!")
                    this.props.onFav(favData, token);
                    this.setState({ disabled: true });
                } else {
                    this.setState({ alreadyAddedFav: true })
                    console.log("it is already in the fav list!")
                    console.log(recipe_id)
                }

            } else {
                this.props.onFav(favData, token);
                this.setState({ disabled: true });
            }
        }
    }





     render() {
       return (
                 <SearchResult
                            disabled={this.state.disabled}
                            key={ig.recipe_id}
                            title={ig.title}
                            imgSrc={ig.image_url}
                            clicked={() => this.onClickedHandler(ig.recipe_id, this.props.token)}
                        >
                        </SearchResult>)}

這是一個簡單的示例,也許您可​​以根據自己的情況進行增強。

 class App extends React.Component { state = { disableds: [], }; handleClick = i => this.setState( currentState => ( { disableds: [ ...currentState.disableds, i ], } ) ); render() { return ( <div className="App"> <Buttons onClick={this.handleClick} disableds={this.state.disableds} /> </div> ); } } const Buttons = ( props ) => { const buttons = [ { text: "foo" }, { text: "bar" }, { text: "baz" } ]; return ( <div> {buttons.map( ( button, i ) => ( <button key={button.text} disabled={props.disableds.includes( i )} onClick={() => props.onClick( i )} > {button.text} </button> ) )} </div> ); }; ReactDOM.render( <App />, document.getElementById( "root" ) ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

我在這里不喜歡的是將onClick處理程序添加到button元素的方式。 這樣,將在每個渲染中重新創建此箭頭功能。 沒什么大不了的,但是我更喜歡使用函數引用。 為了避免這種情況,我們可以將每個按鈕元素提取到其組件中,然后再次使用單獨的處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM