我有一个具有简单层次结构的 React JS 应用程序:ContainingBox 包装了两个 InfoBox 组件。在此示例中,我只想告诉 ContainingBox 组件 1) 已单击某些内容,以及 2) 已单击了哪个 InfoBox(按标签名称)?
这是一些在我的浏览器中运行的基本代码,可以启动和运行这个问题。当您单击页面上的 InfoBox 元素之一时,它会在 console.log 中执行所有操作。
从本质上讲,我想要实现的是,当单击子 InfoBox 元素之一时,我希望 ContainingBox 更改状态(特别是渲染的边框颜色)。
我不确定这里的正确方向是什么。
我使用 React 16.10.2 构建了这个应用程序,但我很乐意阅读将我指向最新的“React 方式”思维的答案。
import React from 'react';
import styled from 'styled-components'
import './App.css';
const StyledInfoBox = styled.div`
width: 100px;
border: solid 1px green;
padding: 10px;
cursor: pointer;
`
class InfoBox extends React.Component {
constructor({blurb}) {
super()
this.state = {
label: (blurb ? blurb.label : ""),
}
this.selectBox = this.selectBox.bind(this);
}
selectBox(e) {
e.preventDefault()
console.log("selectBox")
// how do I tell the ContainingBox component 1) that something has been clicked,
// and 2) which InfoBox (by label name) has been clicked?
}
render() {
const {label} = this.state
return (
<StyledInfoBox onClick={this.selectBox} >
{label}
</StyledInfoBox>
)
}
}
class ContainingBox extends React.Component {
render() {
return (
<div>
<InfoBox key={1} blurb={{label: "Aenean malesuada lorem"}} />
<InfoBox key={2} blurb={{label: "Lorem Ipsum dor ameet"}} />
</div>
)
}
}
function App() {
return (
<div className="App">
<ContainingBox />
</div>
)
}
export default App;