如何在按钮阵列中单击后禁用特定按钮?

问题描述 投票:1回答:1

我的问题是,如何禁用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>)}
javascript arrays reactjs
1个回答
0
投票

这是一个简单的例子,也许你可以根据你的情况加强这个。

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处理程序添加到按钮元素的方式。这样,将在每个渲染中重新创建此箭头函数。没什么大不了但我更喜欢使用函数引用。为避免这种情况,我们可以将每个按钮元素提取到其组件中,并再次使用单独的处理程

© www.soinside.com 2019 - 2024. All rights reserved.