Reactjs 在事件处理程序中使用道具
我试图在事件处理程序中使用道具。这是我代码的一部分Reactjs 在事件处理程序中使用道具,reactjs,event-handling,react-props,Reactjs,Event Handling,React Props,我试图在事件处理程序中使用道具。这是我代码的一部分 class Dashboard extends Component { componentDidMount() { var grid = new Muuri('.grid', { //options... }); grid.on('move', (data) => { console.log('ok') //can't use this.props here );
class Dashboard extends Component {
componentDidMount() {
var grid = new Muuri('.grid', {
//options...
});
grid.on('move', (data) => {
console.log('ok')
//can't use this.props here
);
}
render() {...}
constructor() {...}
}
问题是我无法访问“移动”处理程序中的
this.props
。您可以存储对this.props的引用,并在事件处理程序中引用它
class Dashboard extends Component {
componentDidMount() {
const {prop1name, prop2Name} = this.props;
//OR
const thisProps = this.props;
var grid = new Muuri('.grid', {
//options...
});
grid.on('move', (data) => {
console.log('ok')
//access `this.props` using `thisProps` or access individual properties.
)}
render() {}
constructor() {}
}
或
使用析构函数访问所需的单个属性,然后在事件处理程序中访问这些属性
class Dashboard extends Component {
componentDidMount() {
const {prop1name, prop2Name} = this.props;
//OR
const thisProps = this.props;
var grid = new Muuri('.grid', {
//options...
});
grid.on('move', (data) => {
console.log('ok')
//access `this.props` using `thisProps` or access individual properties.
)}
render() {}
constructor() {}
}
您很可能需要从调用函数的任何位置绑定this
。即使在my arrow函数之后使用.bind(this)命令,console.log(this)也会返回我Undefinedy您正在使用arrow函数,因此this
应该引用与componentDidMount
中相同的this
。你能提供你的问题的可执行示例吗?我同意第一个建议的解决方案,即在定义网格事件之前分解props对象。如果我这样做,我就能够在这个.props中的数组中推送数据?@Phobie这个.props
是只读的。你不能也不应该这样做。而是使用状态提升谢谢,所以我将使用状态而不是道具。问题仍然是一样的,我不能在我的事件处理程序中使用state,也不能在const中复制state,因为它不允许我推送数据,然后在以后使用它们。顺便说一句,这是一个在仪表板上有小部件的网格,当用户移动小部件时,我需要保持小部件的索引移动,并将其发送到RESTAPI以保存用户的小部件配置。