【发布时间】:2018-02-01 19:25:52
【问题描述】:
我有 2 个组件,一个称为 NodeWidget,另一个称为 PopupWidget。在 NodeWidget 中,它有一个分配给它的模型,如下所示:
PopupModel
export class PopupModel {
question: string;
model: string;
constructor(question: string, model: string) {
this.question = question;
this.model = model;
}
}
父组件是NodeWidget,它将Model传递给带有数据的PopupWidget。
NodeWidget
{ this.state.showComponent ?
<PopupWidget model={this.props.popupModel} /> :
null
}
最后在子组件中我们有这样的代码:
export interface PopupWidgetProps {
model: PopupModel;
}
export interface PopupWidgetState { }
export class PopupWidget extends React.Component<PopupWidgetProps, PopupWidgetState> {
constructor(props: PopupWidgetProps) {
super(props);
this.state = { };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this.props);
}
render() {
return (
<div className="popup">
<div className="popup_inner">
<h1>TEST</h1>
<input type="text" value={this.props.model.question} placeholder="Write a question..." />
<button onClick={this.handleClick}>close me</button>
</div>
</div>
);
}
}
我希望能够将输入的值绑定到模型,然后让它更新父组件中的原始模型,我这样做是否正确,因为它似乎不起作用。
【问题讨论】:
-
这不是 React 的工作方式。 React 使用单向流。 Check here to see the difference between Angular's two-way data binding and Reacts unidirectional flow.
-
@ChaseDeAnda Ahh 我明白了,所以您不能直接将输入绑定到模型。如果我使用 onChange 事件,我将如何更新模型?
-
你必须使用回调函数
标签: reactjs typescript