如何绑定'这'到react类之外的函数,后者是来自其他组件的回调
How to bind 'this' to functions outside react class which is a callback from other component?
我有一个React组件,例如:
function callback(params){..
// I need to use this.setstate but this callback function is called
// from other component. How do I bind value of this here
// 'this' of RespProperties
...
}
class RespProperties extends Component { ..
...
}
这个回调函数是从其他组件调用的。如何在此处绑定"this"的值,以便它可以使用该组件的状态?
我真的不明白这个问题。我不知道这是不是你的意思,但如果你想保存"this"临时变量,那么只需创建一个全局数组或单个变量来存储"this"。
var thisTemp;
function callback(params){..
// use variable here
thisTemp.blah();
...
}
class RespProperties extends Component { ..
//Assign this to thisTemp
thisTemp = this;
...
}
您可以分离这个共享函数,将其留在组件之外,然后使用bind
:
function callback(params){
this.setState({ works: true });
}
class RespProperties extends Component {
state = { works: false }
...
render = () => <button onClick={callback.bind(this)}>Click</button>
// ^ here we use .bind(this) to... well...
// bind `this` so we can use it in the function xD
}
class SomeOtherComponent extends Component {
state = { works: false }
...
render = () => <button onClick={callback.bind(this)}>I'm from some other component</button>
}
相关文章:
- 如何将一个JavaScript函数回调为多个函数
- Meteor:异步函数回调异常:onAfterAction
- 从类方法中的 ajax post 函数回调函数更改 javascript 类属性
- jQuery动画函数回调错误
- jquery在html属性中添加函数回调,以便在其他事件中调用
- jquery getjson 函数:回调返回错误的字符串
- postMessage - 多个 postMessage 事件/函数/回调
- 在 Promise 调用的错误函数回调后附加对象的用法是什么
- 单击事件后的 JavaScript 函数回调
- 设置超时函数回调静态变量
- Jquery UI 模式匿名函数回调以打开对话框
- 函数回调、局部变量和 chrome.storage.sync.get
- Jquery Ajax 没有拾取选项参数中指定的函数回调
- 如何在 javascript 中进行函数回调
- 用函数回调封装JavaScript
- jQuery JavaScript嵌套异步函数回调
- Node.js-匿名函数回调
- 函数回调超出范围
- php代码的Javascript函数回调
- 如何使用函数回调在更改时提交表单