簡體   English   中英

在ReactJS中在onClick時添加道具

[英]Add prop when onClick in ReactJS

單擊后,我想更改當前li項目的顏色。

當我單擊道具時如何向道具添加道具(使用數組映射)? 我使用樣式組件

const Li = styled.li`
  color: ${props => (props.checked ? "red" : "green")};
`;

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      items: []
    };
  }

  render() {
    const ShowItems = this.state.items.map((item, index) => {
      return (
        <Li key={index}>
          {item}
          <button onClick={() => this.deleteItemHandler(index)}> Delete</button>
        </Li>
      );
    });

    return (
      <Wrapper>
        <AddItem
          addItemHandler={this.addItem}
          InputValue={this.state.value}
          InputValueHandler={this.inputValue}
        />
        {ShowItems}
      </Wrapper>
    );
  }
}

因此,您需要跟蹤活動索引,並使用它來更改活動組件顏色的顏色。

state ={
 activeIndex: void 0 
}

const Li = styled.li`
   color: ${props => props.checked ? "red" : "green"};
   ;`

deleteItemHandler = (index) => {
  this.setState({
   activeIndex: index
  })
}


render() {
    const ShowItems = this.state.items.map((item, index) => {
      return (
        <Li key={index} checked={index === this.state.activeIndex} > {item} < button onClick={() => this.deleteItemHandler(index)
        }> Delete</button ></Li >
      )
    })

    return (
      <Wrapper>
        <AddItem
          addItemHandler={this.addItem}
          InputValue={this.state.value}
          InputValueHandler={this.inputValue}
        />
        {ShowItems}
      </Wrapper>
    );

嘗試這個

     const Li = styled.li`
       color: ${props => props.checked ? "red" : "green"};
       ;`

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          value: "",
          items: [],
          currentChecked: null
        };
      }

     render() {
        const ShowItems = this.state.items.map((item, index) => {
          return (
            <Li key={index} checked={index === this.state.currentChecked} >
              {item} 
              <button onClick={() => this.setState({currentChecked: index})}>Delete</button >
            </Li >
           )
        })

        return (
          <Wrapper>
            <AddItem
              addItemHandler={this.addItem}
              InputValue={this.state.value}
              InputValueHandler={this.inputValue}
            />
            {ShowItems}
          </Wrapper>
        );

看看在CodeSandBox上工作的這段代碼

import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import styled from "styled-components";

const Li = styled.li`
  color: ${props => (props.checked ? "red" : "green")};
`;

class App extends Component {
  state = {
    value: "",
    items: [],
    selected: -1
  };

  handleChange = e => {
    this.setState({
      [e.currentTarget.name]: e.currentTarget.value
    });
  };

  handleAdd = () => {
    const { items, value } = this.state;
    this.setState({
      items: [...items, value],
      value: ""
    });
  };

  handleRemove = index => {
    const { items, selected } = this.state;
    items.splice(index, 1);
    if (index < selected) index = selected - 1;
    if (index === selected) index = -1;
    if (index > selected) index = selected;
    this.setState({
      items: items,
      selected: index
    });
  };

  handleActiveItem = index => {
    this.setState({ selected: index });
  };

  render() {
    const { value, items, selected } = this.state;
    return (
      <div>
        <input
          type="text"
          value={value}
          name="value"
          onChange={this.handleChange}
        />
        <button
          style={{ margin: "0px 5px" }}
          disabled={!value}
          className="btn btn-sm btn-success"
          onClick={this.handleAdd}
        >
          +
        </button>
        <ul className="li">
          {items.map((item, index) => (
            <Li key={index} checked={selected === index}>
              <span onClick={() => this.handleActiveItem(index)}>{item}</span>
              <button
                style={{ margin: "1px 5px" }}
                className="btn btn-sm btn-danger"
                onClick={() => this.handleRemove(index)}
              >
                X
              </button>
            </Li>
          ))}
        </ul>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

如果不需要處理程序,請忽略它們。 由於這項工作,我了解了styled-components並發現了CodeSandBox。

編輯:

  • <span> inside <li>添加了<span> inside <li>以避免嵌套onClick ,以前的<li> (父級)和<button> (子級)都具有onClick屬性。 “單擊按鈕”觸發了兩個onClick事件,在某些用例中導致意外行為。 您必須在代碼中更正此錯誤
  • 添加了邏輯,可以在刪除項目之前使項目保持選中狀態。
  • 添加了按鈕驗證,以避免在列表中添加空字符串/項目。
  • 還更新了CodeSandBox代碼以反映上述更改。

暫無
暫無

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

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