Reactjs React和数据绑定
我有一个父组件和子组件对,这让我不得不进行数据绑定 顶级组件将呈现新的Reactjs React和数据绑定,reactjs,Reactjs,我有一个父组件和子组件对,这让我不得不进行数据绑定 顶级组件将呈现新的问题组件: <Question updateScore={this.updateScore} /> 问题项componenet更简单: var QuestionItem = React.createClass({ render: function() { return ( <li onClick={this.props.updateScore.bind(this, this.prop
问题
组件:
<Question updateScore={this.updateScore} />
问题项componenet更简单:
var QuestionItem = React.createClass({
render: function() {
return (
<li onClick={this.props.updateScore.bind(this, this.props.optionLabel)}>
{this.props.description}
</li>
);
}
});
另外,如果我注销了正在更新的分数值,那么我会看到它不会更新任何键,而是插入一个未定义的:
{ labelOne: 0, labelTwo: 0, undefined: NaN }
我应该如何绑定此问题?编辑:此答案在问题编辑之前发布。我保留它是因为它可以在将来帮助他人 当您在函数之后执行
()
时,您正在将函数的结果传递给问题组件。这样,当您调用this.props.updateScore
时,您只得到函数的结果,而不是执行它
您需要向下传递它的引用,以便问题组件可以执行或绑定到它。这样,当您调用This.props.updateScope
时,您将得到一个函数,可以使用This.props.updateScope()
或绑定到它This.props.updateScope.bind(This)
删除那些()
,如下所示:
<Question updateScore={this.updateScore} />
您应该准备好了此警告是合法的,因为您的代码将
QuestionItem
而不是Question
绑定到updateScore()
。我建议从两个选项中选择一个:
1) 由于在问题
中有optionLabel
属性,请将函数绑定到那里,以便它可以使用正确的此
var optionList = this.state.options.map(function(option) {
return (
<QuestionItem optionLabel={option.optionLabel} description={option.description}
updateScore={this.updateScore.bind(this, option.optionLabel)} key={option.key} />
);
}.bind(this));
实际反应:
通过提供
null
而不是this
,您将允许React做自己的事情。哎呀,这是一个输入错误。它没有那些参数。啊,我明白了,我应该删除我的答案吗@我仍然认为你的话可能对别人有用。
<Question updateScore={this.updateScore} />
var optionList = this.state.options.map(function(option) {
return (
<QuestionItem optionLabel={option.optionLabel} description={option.description}
updateScore={this.updateScore.bind(this, option.optionLabel)} key={option.key} />
);
}.bind(this));
var wrapperFunc = function(optionLabel) {
this.props.updateScore(optionLabel);
}.bind(this, this.props.optionLabel);
return (
<li onClick={wrapperFunc}>
{this.props.description}
</li>
);
scope.props.updateScore.bind(null, this.props.optionLabel)