gpt4 book ai didi

javascript - 调用 React 函数不起作用

转载 作者:行者123 更新时间:2023-11-30 15:03:31 24 4
gpt4 key购买 nike

我的代码如下,我希望我的结果是“Hello Mr. John Doe”。

function formatname(name) {
return name.fullName;
};

const name = {
firstName: 'John',
lastName: 'Doe',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};

const getName = (
<h1>Hello Mr. {formatname(name)}</h1>
);

ReactDOM.render(
getName,
document.getElementById('root')
);

但是当我保存它时返回的是“Hello Mr.”,这是我在变量 fullName 中的错误。

最佳答案

在您的代码中:

const name = {
firstName: 'John',
lastName: 'Doe',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};

这不再引用您的变量名。要解决,您需要将其绑定(bind)回您声明的名称:

formatname(name).bind(name)()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

关于javascript - 调用 React 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46147506/

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