【问题标题】:Raising and Handling events in React在 React 中引发和处理事件
【发布时间】:2020-10-23 18:41:48
【问题描述】:

我想在单击按钮时增加 Items 组件的值,该按钮由其子组件 Item 处理。项目有一个键值对数组,这个值需要递增和呈现 这是代码

//parent component
class Items extends React.Component{
  state={
    items:[{ id: 1, value: 9 }, 
           { id: 2, value: 10 }, 
           { id: 3, value: 0 }]
  }
  
  handleIncrement=()=>{
   
  //need to increment items.value on each button click increment. How can I access it
    
  }

  render(){
    return(
      <div>
        <h2>Increment item on the list From Parent</h2>
        {this.state.items.map(item=>(<Item key={item.id}
          value={item.value} id={item.id} onIncrement={this.handleIncrement}
        />))}
        
      </div>
    )
  }
}


//child component
class Item extends React.Component{

  getValue=()=>{
    let {value}=this.props;
    return value===0?'Zero':value
  }

  render(){
    return(
      <div>
        <span>{this.getValue()}</span>
        <button  onClick={this.props.onIncrement}>Increment</button>

      </div>
    )
  }
}

请帮帮我。

【问题讨论】:

  • 你试过使用setState吗? setState
  • 不,我对访问每个值的 id 有疑问。因为事件是由另一个组件处理的,所以我们需要传递 id 对吗?

标签: javascript arrays reactjs object


【解决方案1】:
state = {
  items: [{ id: 1, value: 9 }, { id: 2, value: 10 }, { id: 3, value: 0 }]
};

handleIncrement = id => event => {
    event.preventDefault();
    const s = JSON.parse(JSON.stringify(this.state.items)); // dereference
    const ndx = s.map(e => e.id).indexOf(id);
    s[ndx]["value"]++;
    this.setState({ items: s });
  };

这里有一个沙盒,您可以预览实现: https://codesandbox.io/s/wonderful-voice-kkq7b?file=/src/Increment.js:380-803

【讨论】:

    【解决方案2】:

    或者您可以通过数组索引而不是对象 id 进行更新

    //parent component
    class Items extends React.Component {
      state = {
        items: [{ id: 1, value: 9 }, { id: 2, value: 10 }, { id: 3, value: 0 }]
      };
    
      handleIncrement = e => {
        //need to increment items.value on each button click increment.How can i access it
        const id = e.target.id;
        const tempItems = this.state.items;
        tempItems[id] = {...tempItems[id], value: ++tempItems[id].value}
        this.setState((prevState)=>({ items: tempItems}));
    
      };
    
      render() {
        return (
          <div>
            <h2>Increment item on the list From Parent</h2>
            {this.state.items.map((item,i) => (
              <Item
                key={item.id}
                value={item.value}
                id={item.id}
                index={i}
                onIncrement={this.handleIncrement}
              />
            ))}
          </div>
        );
      }
    }
    
    //child component
    class Item extends React.Component {
      getValue = () => {
        let { value } = this.props;
        return value === 0 ? "Zero" : value;
      };
    
      render() {
        return (
          <div>
            <span>{this.getValue()}</span>
            <button id={this.props.index} onClick={this.props.onIncrement}>Increment</button>
          </div>
        );
      }
    }
    

    【讨论】:

      【解决方案3】:

      您可以添加id 作为按钮名称

      <button name={this.props.id} onClick={this.props.onIncrement}>Increment</button>
      

      然后在你的函数中使用它

       handleIncrement= e =>   
         this.setState({ items: this.state.items.map(item =>
                    item.id == e.target.name ? {...item, value: item.value++ } : item ) })
        
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-12
        • 2017-03-14
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        • 2011-06-29
        • 2014-09-05
        相关资源
        最近更新 更多