在ReactJS中点击时添加道具

时间:2019-02-25 06:46:42

标签: javascript reactjs styled-components

我想在单击时更改当前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>
    );
  }
}

3 个答案:

答案 0 :(得分:0)

因此,您需要跟踪活动索引,并使用它来更改活动组件颜色的颜色。

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>
    );

答案 1 :(得分:0)

尝试一下

     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>
        );

答案 2 :(得分:0)

查看此适用于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>以避免嵌套onClick,以前的<li>(父级)和<button>(子级)都具有onClick属性。 “单击按钮”触发了两个onClick事件,在某些用例中导致意外行为。 您必须在代码中更正此问题
  • 添加了逻辑,可在删除项目之前使项目保持选中状态。
  • 添加了按钮验证功能,以避免在列表中添加空字符串/项目。
  • 还更新了CodeSandBox代码以反映上述更改。