单击后如何在按钮数组中禁用特定按钮?

时间:2018-10-04 22:07:51

标签: javascript arrays reactjs

我的问题是,如何根据单击来禁用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>)}

1 个答案:

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