在 React 中引发和处理事件



我想在按钮单击时增加项目组件的值,该按钮由其子组件 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>
)
}
}

请帮我解决这个问题。

您可以添加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 ) })

或者你可以通过数组索引而不是对象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>
);
}
}
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

相关内容

  • 没有找到相关文章

最新更新