javascript - 在反应中调用儿童中的函数?
问题描述
我有一个包含多个Views
. 每个View
都有一些映射的 child Entities
。这些实体中的每一个都有一个关于它是否被折叠/隐藏的状态,称为:this.state.show
。每个Entity
都有一个切换show
状态的按钮。这一切都很好。
我想做的是在View
同时显示或隐藏的按钮上添加一个按钮Entities
。我认为这很简单,但有几个复杂的因素:
- 我最终将
Views
在应用程序中有多个,每个都以不同的方式显示相同的数据,因此存储show
在提升的道具中并不是一个很好的选择。我也不想将 UI 状态存储在文件数据中,因为这让我很不爽。 - 它使我更容易理解当状态直接存储在
Entity
作为状态而不是道具时发生了什么View
- React 文档(以及每个在线的人)都说你不应该基于 props 的变化来建立状态,并且数量
Entities
会经常变化。这就是为什么我不想将子项的状态存储在父项中的原因,因为如果我这样做并且实体发生了变化,那么我必须以某种方式将道具的变化转换为状态的变化,这是强烈警告的。 - 如果我要使用事件,这些事件可能会从一个溢出
View
到另一个。
在这里追求的正确策略是什么?我认为“反应”不够吗?
查看.jsx
import React, { Component } from 'react'
import Entity from './Entity.jsx'
import Filter from './Filter.jsx'
class View extends Component {
render() {
return (
<div className="view main">
{this.props.entities ? this.props.entities.map(
(e, i) => (
<Entity
entity={e}
propertyTypes={this.props.propertyTypes}
key={i}
index={i}
taglists={this.props.taglists}
ee={this.props.ee}
/>
)
) : ""}
</div>
)
}
}
export default View
实体.jsx
import React, { Component } from 'react'
import Property from './Property.jsx'
import Event from './Event.jsx'
import Relationship from './Relationship.jsx'
class Entity extends Component {
constructor (props) {
super(props);
this.state = {
show: true
}
this.showHide = this.showHide.bind(this)
}
showHide() {
this.setState({
show: !this.state.show
})
}
render() {
return (
<div className="entity" id={this.props.entity.name}>
<div className="entity-header">
<h2>
<input
type="text"
value={this.props.entity.name}
onChange={this.emit}
data-original={this.props.entity.name}
data-index={this.props.index}
data-event="rename"
></input>
</h2>
<button
className="entity-collapse"
data-index={this.props.index}
onClick={this.showHide}
>{this.state.show ? "-" : "+"}</button>
</div>
<div className={this.state.show ? "entity-content" : "entity-content hidden"}>
...
removed for clarity
...
</div>
</div>
)
}
}
export default Entity
解决方案
您的状态应该只在父组件中,而不是任何子组件中。然后,您会将您的函数和状态作为道具传递给孩子们。
推荐阅读
- java - 重构方法时选择什么方法,使其响应干净代码的原则?
- android - Android oboe c++ 有些声音在播放时失真
- neo4j - Neo4j APOC 触发器,手动索引 - 小写属性值
- selenium - 使用 Protractor 和 webdriver 在自动化测试中启用剪贴板
- html - HTML / CSS导航栏下拉菜单在后台?
- html - 我正在尝试创建如下图所示的网格
- c# - c# .dbf 使用 jet 4.0 获得随机编码
- php - 复制 Drupal 网站并转移到另一个主机和域
- c# - 服务器上是否需要 MS Office 才能使用 Microsoft.Excel.interop
- gradle - 当出现任何标准错误时,Gradle 构建失败