我试图基于MobX可观察值在App.js中呈现一个组件 . 我想定义一个采用组件和一些新的自定义道具分配的动作 . 这就是我现在拥有的:
// App.js inside render()
{ ui_store.main_area_sequence }
.
// ui_store.js
// OBSERVABLES / state
main_area_sequence = <ChoosePostType />;
// ACTIONS / state mutators
update_ui_in_main_section(ComponentTag, props) {
this.main_area_sequence = <ComponentTag {props} />
}
组件参数按预期工作 . 但我不能让道具论证起作用 . 理想情况下,我会用它来构建类似的东西:
<ChildComponentToBeSwitchedIn name={ui_store.name} handleClick={this.handleClick} />
作为一个示例, <ChoosePostType />
中的按钮可能会将 main_area_sequence
中的可观察值重新分配给上面的点击 .
有没有人知道如何将道具作业作为参数传递给他们?
2 回答
我怀疑你是在思考这个问题 .
回想一下,JSX只是JavaScript . 当你输入这个:
......你真的写这个:
但是,如果要渲染的组件是动态的,该怎么办?那's fine; it still works. For example, suppose we kept the component and props in our React component' s
state
:上面的JSX转换为这个JavaScript:
如你所见,我们从
this.state.dynamicComponentProps
获得道具,但我们也从this.props.name
添加一个name
道具,从this.handleClick
添加onClick
道具 . 您可以想象this.handleClick
调用this.setState
来更新dynamicComponent
和dynamicComponentProps
.实际上,您不必想象它,因为您可以在下面的代码片段中看到它:
我上面使用了普通的旧React状态,但是同样的东西适用于MobX,如下所示 . (我之前从未使用过MobX,所以我的代码可能不是惯用的,但希望你能得到这个想法 . )
我不得不在这里使用
decorate
,因为Stack Overflow 's Babel configuration doesn' t包含装饰器,但我在CodeSandbox上发布了与装饰器相同的东西:https://codesandbox.io/s/qlno63zkw4如果你没有传递道具,那么不要包含道具参数 .