reactjs - 在 React JS 中,我如何告诉父组件子组件发生了什么事?
问题描述
我有一个具有简单层次结构的 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;
解决方案
您通过道具将回调从父组件传递给子组件。
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
changeNameTo = (newName) => this.setState({name: newName})
render() {
return (
<div>
<h1>{this.state.name}</h1>
<p>
<Child callbackExample={this.changeNameTo} />
</p>
</div>
);
}
}
然后你有你的 Child 组件。
class Child extends Component {
render() {
return(
<div>
<button onClick={() => this.props.callbackExample("Doggos")}>
Click me
</button>
</div>)
}
}
当您单击按钮时,将调用回调设置父级的状态,然后在父级重新渲染时反映出来。
推荐阅读
- selenium-webdriver - 使用代理自动到 Instagram 注册页面
- laravel - 在 hasMany-relationship 上限制为 1
- python - 是否有任何功能可以帮助我在 PySpark 中转换日期和字符串格式
- javascript - 如何获取作为对象数组一部分的输入的当前值?
- java - 缩小最小手指距离的大小
- arm - 对齐/未对齐 AXI 传输是什么意思
- python - 我应该将特征缩放与多项式回归与 scikit-learn 结合使用吗?
- facebook - 以编程方式创建可见 Facebook 帖子的最简单/最便宜的方法是什么?
- log4j2 - 错误消息打印在所有日志文件中
- php - 用于附件上传的 Twitter API