我不确定在复杂情况下如何从我的组件中分离数据: 想象一下,我正在构建一个标签式视频游戏容器,其中包含如下API:
const App = props =>
<VideoGameContainerGroup tabbed searchable>
<VideoGame id="cool-game-22" name="Cool Game, part 22" genre="RTS">
<CoolVideoGame /> {/* Implementation goes here */}
</VideoGame>
<VideoGame id="something-wild" name="Craziest game ever" genre="button">
<div>
<h1>Some inline defined game-like component</h1>
<button>click me</button>
</div>
</VideoGame>
{/* ... more games .. */}
</VideoGameContainerGroup>
它不需要知道游戏的实现,但想要以某种方式标记游戏,以便它可以索引它们,执行搜索和其他一些UI的东西:
class VideoGame extends component {
getDynamicBio() {
return `Hi, I am game ${this.props.name} fom genre ${this.props.genre}`;
}
render() {
<div className="some-VideoGameContainer-boilerplate">
{this.props.children /* implementation */}
</div>
}
}
class VideoGameContainerGroup extends Component {
render() {
return (
<div>
<div className="all-games">
{this.props.children}
</div>
{/* ... code, which through sub componentes resolve to: */}
<div className="SearchableGamesTabHeader">
{React.Children.map(this.props.children, (game, i) => {
{ /* but here I need access to complex class methods */}
<span>Game bio: {game.getDynamicBio()}</span>
{ /* this won't work */ }
})}
</div>
</div>
)
}
}
我考虑过导出一包帮助函数,例如:
const getDynamicBio = (component) =>
`Hi, I am game ${component.props.name} fom genre ${component.props.genre}`
但这些方法与VideoGame容器及其数据相关联,以这种方式处理它似乎很奇怪。
我考虑过这样做:
<VideoGame videoGameData={ new VideoGameData({ id: 'cool-game-22', genre: 'RTS' }) }>
<GameImplementation />
</VideoGame>
然后通过VideoGame.props.videoGameData访问数据。但我的经纪人告诉我这是错的。
VideoGame确实是包含所有元数据的组件,从OO方法我将存储与该类相关的方法。我如何在React中以可维护的方式解决这个问题?
答案 0 :(得分:0)
我们不会在父级中直接访问子组件方法。如果你想要那样做,可以这样做。
class VideoGameContainerGroup extends Component {
render() {
return (
<div>
<div className="all-games">
{this.props.children}
</div>
{/* ... code, which through sub componentes resolve to: */}
<div className="SearchableGamesTabHeader">
{React.Children.map(this.props.children, (ChildEl, i) => {
<ChildEl complexMethodAsCb = {()=>//pass in particular work you need to do say, on click} neededPropsInComplexMethod={...}/>
<span>Game bio: {game.getDynamicBio()}</span>
</ChildEl/>
})}
</div>
</div>
)
}
}
因此,我们将数据和方法从顶部反应出来。我们传递父母所拥有的任何已知数据和方法,儿童和儿童在特定方法之后/之前调用这些数据和方法。
此外,我们还尝试从组件中删除所有数据/方法。这就是一个名为flux的模式。您可以检查redux以进一步阅读并简化它。