从另一个组件更新一个组件



我是React的新手,我想知道是否可以根据来自另一个组件的事件更新另一个组件的内容。

我有两个反应组分。当页面加载时,其中一个组件将其数据加载到它,而另一个组件应该根据第一个组件的onClick方法呈现其数据。

其中一个组件从API加载数据,然后我将其显示在列表中。然后,我有一个方法,应该处理被单击的项目称为itemClicked,当一个项目被单击时,其他组件中的数据应该更新。
itemClicked = () => {
// Get the ID of the clicked item, and use it in the other component
console.log(e.target.attributes[0].value);
}
// ...
<ul>
{items.map(item => (
<li onClick={this.itemClicked} key={item._id} itemID={item._id}> {item.name} </li>
))}
</ul>

我现在这可能是一个不好的问题,但我是React的新手,并试图学习更多关于状态和道具。

编辑。

这是我加载两个组件的父组件:

class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
currentItem: {}
}
}

onItemClick(item) {
this.setState({
currentItem: item
})                                        

}
render() {
return <>
<div className='dashboard'>
<div className='dashboard__wrapper'>
<SelectItem onItemClick="{this.onItemClick}" />
<EditItem item="{this.state.currentItem}" />
</div>
</div>
</>
}
}
export default Dashboard

我也更新了SelectItem组件:

itemClicked = (e) => {
console.log(e.target.attributes[0].value);
if (this.props.onItemClick) {
this.props.onItemClick(e.target.attributes[0].value)
}
}

但是现在它抱怨这一行:

this.props.onItemClick(e.target.attributes[0].value)

不是函数:

Uncaught TypeError: this.props.onItemClick is not a function

当然可以。

如果列表组件和视图组件都在同一个父组件中。父组件可以有一个状态属性,例如currentItemcurrentItem将通过将回调作为属性传递给列表组件来设置。当列表项被点击时,回调函数应该被调用。

//List Component
itemClicked = () => {
// Get the ID of the clicked item, and use it in the other component
console.log(e.target.attributes[0].value);
//call the callback
if(this.props.onItemClick){

this.props.onItemClick(e.target.attributes[0].value)
}
}
...
<ul>
{items.map(item => (
<li onClick={this.itemClicked} key={item._id} itemID={item._id}> {item.name} </li>
enter code here
))}
</ul>

页面组件
this.state = {
currentItem: {}
}
onItemClick(item){
this.setState({
currentItem: item
})                                        
}
render(){
return <>
<ListComponent onItemClick={this.onItemClick} />
<ViewComponent item={this.state.currentItem} />
</>
}