reactjs - 在父组件中的事件之后更新子组件中的道具?
问题描述
取2个组件:
父组件子组件
ParentComponent 在 render 中设置 ChildComponent:
render() {
return (
<ChildComponent x='default value' />
)
}
然后,ParentComponent 想要将 x='default value' 更改为 'hello',可能是为了响应 onClick 事件。
我认为我的困惑是,我知道如何设置初始变量 x,但不知道以后如何更改它。
解决方案
将您的状态提升到您的状态Parent
并将其传递给Child
viaprops
const Parent = () =>{
const [title, setTitle] = useState('foo')
return(
<>
<Child title={title} />
<button onClick={() => setTitle('bar')}>Change to bar</button>
</>
)
}
const Child = ({ title }) => <div>{title}</div>
对于class
基于组件
class Parent extends React.Component {
state = { title: 'foo' }
render() {
const { title } = this.state
return (
<>
<button onClick={() => this.setState({ title: 'bar' })}>Change to bar</button>
<Child title={title} />
</>
)
}
}
class Child extends React.Component {
render() {
const { title } = this.props
return <div>{title}</div>
}
}
推荐阅读
- c# - 我通过倾斜手机来控制游戏对象,并且需要在游戏开始时手机旋转时保持平衡
- angular - Angular - 全屏时未触发 @HostListener('window:keydown.escape', ['$event'])
- python - 浏览器未对大文件发起范围请求
- python - 使用 panda 数据框作为具有两个参数的函数的输入时出现错误消息
- python - 使用云功能在 Cloud Storage 中编写警报策略列表
- docker - LocalStack 卡在“等待所有 LocalStack 服务准备就绪”消息中
- openfeign - 开放的伪装类线程是否保存?(GsonDecoder, OkHttpClient)
- gitlab - 如果外部 url 没有改变,gitlab runners 是否需要在迁移后重新注册?
- node.js - 在 linode 虚拟主机上部署 node js/express web 应用程序
- c# - 编写 DbContext 扩展方法