在我的ReactJS代码中,通过使用refs,我在各个按钮单击的View组件内部调用Action组件的addRecord和deleteRecord函数。但是我收到了一个错误(在下面发布)。请告诉我的代码有什么问题?
错误:
Uncaught TypeError: Cannot read property 'deleteRecord' of undefined
at new View (index.js:32602)
at index.js:28264
...
View.jsx
import React from 'react';
import Action from './Action.jsx';
class View extends React.Component {
constructor() {
super();
this.refs.actionHandler.deleteRecord = this.refs.actionHandler.deleteRecord.bind(this);
this.refs.actionHandler.addRecord = this.refs.actionHandler.addRecord.bind(this);
};
render() {
return (
<div className="container">
<ul className="list-group">
{this.props.store.map((eachRecord) => (
<li className="list-group-item" key={eachRecord.id}>{eachRecord.name}
<button style={{float:'right'}} onClick={this.refs.actionHandler.deleteRecord(eachRecord)}>Delete</button></li>))}
</ul>
<input type="text" ref="inputElement"/>
<button onClick={this.refs.actionHandler.addRecord(this.refs.inputElement)}>Add</button>
<Action ref="actionHandler" store={this.props.store} updateStore={this.props.updateStore} />
</div>
);
}
}
export default View;
Action.jsx
import React from 'react';
import Dispatcher from './Dispatcher.jsx';
let recordId=3;
class Action extends React.Component {
render() {
return (
<div>
<Dispatcher updateStore={this.props.updateStore} ref="dispatcher" />
</div>
);
};
addRecord(input) {
const inputElement = input;
const text = inputElement.value.trim();
inputElement.value = '';
inputElement.focus();
++recordId;
var newRecord = {name: text, id: recordId};
var newStore = this.props.store;
newStore.push(newRecord);
this.refs.dispatcher.dispatchChanges(newStore);
};
deleteRecord(record) {
var newStore = this.props.store.filter(r => r !== record);
this.refs.disptacher.dispatchChanges(newStore);
}
}
export default Action;
答案 0 :(得分:0)
我正在查看你的代码而我看不到你在哪里传递deleteRecord
<Action ref="actionHandler"
store={this.props.store}
updateStore={this.props.updateStore} />