繁体   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