gpt4 book ai didi

javascript - 将 this 绑定(bind)到 React 中的嵌套函数

转载 作者:行者123 更新时间:2023-12-03 13:58:03 24 4
gpt4 key购买 nike

在处理嵌套函数时如何将 this 绑定(bind)到 React 组件?

这是一个骨架示例。 function2 嵌套的原因是您可以访问 function1

中定义的变量
class View extends Component{

constructor(props){
this.function1 = this.function1.bind(this);

this.state = {
a = null;
}
}

componentDidMount(){
function1();
}

function1(){
console.log(this); //will show the component correctly

var param1 = 10;

//call a second function that's defined inside the first function
function2();

function function2(){
console.log(this); //undefined

var a = param1*2;

this.setState({ a : a}); //won't work because this is undefined
}
}

render(){
return(
<div>
<p> Hello </p>
</div>
)
}
}

最佳答案

为什么不直接使用箭头函数呢?这将确保 this 被正确引用。我假设您可以使用 ES6

function1 = () => {
console.log(this);

var param1 = 10;

const function2 = () => {
console.log(this);

var a = param1*2;

this.setState({ a });
}

function2(); // inkove the function
}

或者,如果您只想使用 ES5,那么这也可以

function1() {
console.log(this);

var param1 = 10;

function function2() {
console.log(this);

var a = param1*2;

this.setState({ a });
}

function2.bind(this)() // to invoke the function
}

关于javascript - 将 this 绑定(bind)到 React 中的嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48676650/

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