gpt4 book ai didi

reactjs - 无法将函数传递给 props

转载 作者:行者123 更新时间:2023-12-03 14:15:20 25 4
gpt4 key购买 nike

我从React开始,似乎props只接受值而不接受函数?当我尝试执行此操作时出现错误:

var Hello = React.createClass({
render: function() {
return (
<div>
hey there! {this.props.x}
</div>
);
},
calcul: function(a, b){
return a*b
}
});

React.render(
<Hello x={this.calcul(5, 6)}/>,
document.getElementById('content')
)

我得到这个Uncaught TypeError: this.calcul is not a function

但是当我使用x={this.calcul}时,它会默默地失败。

最佳答案

this.calcul 不存在,因为在本例中 this 绑定(bind)到全局上下文。如果您想将 calcul 的结果作为 prop 传递:

function calcul(a, b) {
return a*b;
}

var Hello = React.createClass({
render: function() {
return (
<div>
hey there! {this.props.x}
</div>
);
},
calcul: calcul
});

React.render(
<Hello x={calcul(5, 6)} />,
document.getElementById('content')
);

因此,这里 30 将作为 prop x 传递,并且您的组件将具有 calcul 函数。

关于reactjs - 无法将函数传递给 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32389036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com