【发布时间】:2020-01-30 22:04:56
【问题描述】:
我有一个名为:List.js 的页面,它呈现组件:Box 用于 List 页面上的每个项目。我的 List.js 还包含一个名为:MainSpace 的组件。现在每个 Box 组件都将包含一个 button 和一个 onClick 函数。根据您单击的 Box 组件,我想用来自该特定 Box 组件的数据填充 MainSpace,但我似乎无法弄清楚如何做到这一点。
render() {
for (let index in data) {
list.push(
<Box data={data[index]}/>
);
}
return (
<div>
{list}
<MainSpace>
</div>
);
}
现在 Box 组件看起来像这样:
class Box extends Component {
fillMainSpace(){
//Send this.prop.data to the list.js file and fill the MainSpace component from there I think?
}
render(){
return (
<div>
<span>{this.props.data.text}</span>
<button onClick={this.fillMainSpace}></button>
</div>
);
}
}
Mainspace 没有太多。例如,我只想从 Box 组件的单击按钮中加载 this.props.data.image。即使console.log(this.props.data); 也足够了。在每个<Box> 组件中调用<MainSpace> 组件不是一种选择,因为这会导致大量不必要的额外组件。
所以我的问题是:
如何访问<Box> 组件的单击按钮的this.props.data 并在我的<MainSpace> 组件中使用它?
编辑: 添加 MainSpace 组件:
class MainSpace extends Component {
render(){
return (
<div>
{this.props.data.image}
</div>
);
}
}
【问题讨论】:
标签: javascript reactjs