1
在我的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;
請參閱該issue.https更大explainination這個問題://stackoverflow.com/questions/46445667/calling-a-function-using-ref-值功能於reactjs拋出錯誤?noredirect = 1#comment79849240_46445667 – Agha