簡體   English   中英

做出反應。 如何在點擊時在元素中添加 class?

[英]React. How to add class in element on click?

我是反應新手。 目前我正在創建一個用於學習目的的應用程序。 我被困在試圖改變點擊按鈕的顏色。 當我點擊一個按鈕時,所有按鈕的顏色都會改變。 但我只需要激活一個按鈕,而其他按鈕不激活。 當我點擊不同的按鈕時,前一個活動按鈕失去其 class 並變為非活動狀態。 你能幫幫我嗎?

state = {
  clicked: false
};

timeChangeHandler = () => {
  this.setState({ clicked: true });
};

render() {
  return (
    <div>
      <button
        type="button"
        className={
          this.state.clicked
            ? "list-group-item list-group-item-action active"
            : "list-group-item list-group-item-action"
        }
        onClick={this.timeChangeHandler}
      >
        8:00
      </button>

      <button
        type="button"
        className={
          this.state.clicked
            ? "list-group-item list-group-item-action active"
            : "list-group-item list-group-item-action"
        }
        onClick={this.timeChangeHandler}
      >
        9:00
      </button>
    </div>
  );
}

您的解決方案看起來像這樣。

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            activeButton: 0
        };
    }

    render() {
        const { activeButton } = this.state;

        return (
            <div>
                <button
                    className={ activeButton === 0 && "active" }
                    onClick={() => this.setState({activeButton: 0})}
                />

                <button
                    className={ activeButton === 1 && "active" }
                    onClick={() => this.setState({activeButton: 1})}
                />

                <button
                    className={ activeButton === 2 && "active" }
                    onClick={() => this.setState({activeButton: 2})}
                />
            </div>
        );
    }
}

這是一個簡單的示例,說明如何做到這一點。 我 map 按鈕並使用索引作為點擊值。 但是,如果您在代碼中靜態使用按鈕,則可以使用@Kyle 的解決方案。

 const buttons = [ { name: "foo" }, { name: "bar" }, { name: "baz" } ]; class App extends React.Component { state = { clicked: null }; handleClick = id => this.setState({ clicked: id }); render() { return ( <div> {buttons.map((button, index) => ( <button className={this.state.clicked === index && "clicked"} onClick={() => this.handleClick(index)} > {button.name} </button> ))} </div> ); } } ReactDOM.render(<App />, document.getElementById("root"));
 .clicked { background-color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root" />

暫無
暫無

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

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