【问题标题】:Adding and removing element on an Array from different button clicks通过不同的按钮单击在数组上添加和删除元素
【发布时间】:2021-06-17 14:23:30
【问题描述】:

在 html 上我有三个按钮每个按钮负责一个数组的特定索引。 当第一次按下它应该在提供的索引中插入元素,如果再次按下它应该删除元素。 Button 应该切换并且 Array 应该保留前一个元素而不删除元素:

例如: 开

第一次按下所有三个按钮

那么数组应该看起来像这样arr= [1,2,3]

开启

再次按下按钮 2

数组应该是arr=[1,,3] HTML:

<button onClick="test(1,0)">button 1</button>
<button onClick='test(2,1)'>button 2 </button>
<button onClick='test(3,2)'>button 3 </button>

JS:

const arr=[]

let state
const test = (name,index)=>{
  state= !state
  if(state){
     arr[index]=name
  }else{
    arr.splice(index,1)
  }
  
  console.log(arr)
 
}

【问题讨论】:

  • splice 从数组中删除元素,因此不会保留您的位置。相反,我认为您想用null 替换array[index]。这能解决你的问题吗?请包括确切的错误/您的代码实际遇到的问题。
  • 您对splice 的使用会删除索引并缩短数组,您也不能将索引显式设置为空,因此如果您希望这样做,则需要创建一个新数组镜像前一个但不分配相关索引。不过,这似乎是一个脆弱的模式。
  • 您对onClick 函数的调用也是错误的。在进行函数调用时,您需要使用{},因为目前您只是在解释一个字符串。例如你需要做onClick={() =&gt; test(1,0)}
  • @Ranjan Raj Shrestha 如果首先单击第三个按钮,您希望会发生什么?你会期待[null, null, 3] 还是[3]

标签: javascript arrays reactjs if-statement state


【解决方案1】:

您可以尝试arr.splice(index, 1, undefined); 您不能在数组中的两个值之间有“无”,它必须是某物,并且要表示“无”,您可以在 null 和 undefined 之间进行“选择”(取决于您的用例,您应该选择一个而不是另一个)。你也可以用未定义的值初始化你的数组。

【讨论】:

  • 可以在数组中没有任何内容,但您不能为索引分配任何内容。
【解决方案2】:

[编辑]:最初的想法,现在使用reactjs,并使用“名称”的数据属性和css类来设置和确定按钮状态。

class Buttons extends React.Component {
  constructor(props) {
    super(props);
    this.state = [undefined, undefined, undefined];
    this.handleClick = this.handleClick.bind(this);
    this.getLogBox = () => document.querySelector("#Log");
  }
    
  log(...txt) { 
      this.getLogBox().textContent += `${txt.join("\n")}\n`;
  }
  
  logClear() { 
      this.getLogBox().textContent = ``;
  }
  
  setState() {
    this.state = [...document.querySelectorAll("[data-button-name]")]
      .map( btn => btn.classList.contains("on")  ? 
        +btn.dataset.buttonName : 
        undefined );
  }
  
  handleClick(evt) {
    const origin = evt.target;
    
    if (origin.dataset.clear) {
      return this.logClear();
    }
    
    if (!origin.dataset.showstate) {
      origin.classList.toggle("on");
      this.setState();
    } else {
      this.log(`Current state [${this.state}]`);
    }
  };
  
  render() {
    return (
    <div>
      <button data-button-name="1" onClick={this.handleClick}></button>
      <button data-button-name="2" onClick={this.handleClick}></button>
      <button data-button-name="3" onClick={this.handleClick}></button>
      <button data-showstate onClick={this.handleClick}>Show state</button>
      <button data-clear onClick={this.handleClick}>Clear log</button>
    </div>
    );
  }
}

ReactDOM.render(
  [<Buttons />, ( <pre id="Log"></pre> )],
  document.body
);
button {
  margin-right: 5px;
}

button[data-button-name]:before {
  content: 'Off';
}

button[data-button-name].on:before {
  content: 'On';
}
<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>

[原答案] 使用inline event handlers 通常不是一个好主意。这是一个使用event delegation 为三个按钮添加处理程序的sn-p。它使用data-attrributes 记录“推送状态”。

document.addEventListener("click", handle);
const nButtons = document.querySelectorAll("button[data-push-state]").length;
let pushedStates = [...Array(nButtons)];

function handle(evt) {
  if (evt.target.dataset.index) {
    console.clear();
    const isPushed = !!(+evt.target.dataset.pushState);
    evt.target.dataset.pushState = +(!isPushed);
    pushedStates = [...document.querySelectorAll("[data-push-state]")]
      .map(btn => !!(+btn.dataset.pushState) ? +btn.dataset.index : undefined);
    console.log(`pushedStates now: [${pushedStates}]`);
  }
}
<button data-index="1" data-push-state="0">button 1</button>
<button data-index="2" data-push-state="0">button 2</button>
<button data-index="3" data-push-state="0">button 3</button>

【讨论】:

  • 这是一个 React 问题,所以 onClick 不是普通的内联处理程序,而是 JSX 事件语法。
  • 我明白了。我不是那么精通反应。我想 OP 可能会采用 handle 方法
猜你喜欢
  • 1970-01-01
  • 2020-10-19
  • 2021-03-03
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多